I'm trying to call a jQuery function from a link's onClick attribute but I get the following error: Uncaught TypeError: Drupal.behaviors.main.test is not a function.
I created a simple module that will create a block displaying a list of events. The block template will output the following HTML code:
<ul id="events">
<li><a href="#" onclick="Drupal.behaviors.main.test(1)">Event1</a></li>
<li><a href="#" onclick="Drupal.behaviors.main.test(2)">Event2</a></li>
</ul>
Each link has a onClick attribute calling Drupal.behaviors.main.test($id).
On my theme's info file, I include a test.js file with the following code:
(function ($) {
Drupal.behaviors.main = {
attach: function(context, settings) {
$(function test() {
console.log('yo')
});
$('#home').slick({
//init slick
});
}
}
})(jQuery);
When the document is ready, slick plugin is well initialized and test() is called so I get 'yo' on the console. It's when I click the links that I get the error, so I'm thinking about a scope problem since the function is called from a module but is defined on my theme. Does anyone have any idea?
Thanks in advance!
--EDIT-- Thank to rémy, I managed to resolve my issue, here's what I did: My block outputs the following HTML:
<ul id="events">
<li>
<a href="#" id="1" class="whatever">Event1</a>
</li>
<li>
<a href="#" id="2" class="whatever">Event2</a>
</li>
</ul>
And on my test.js file:
(function ($) {
Drupal.behaviors.main = {
attach: function(context, settings) {
$('.whatever').click(function() {
console.log(this.id);
});
$('#home').slick({
//init slick
});
}
}
})(jQuery);