0

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);
1

use an id on your anchors, no onclick:

<li><a href="#" id="whatever">Event2</a></li>

then use the click event on it in the behavoir:

(function ($) {
    Drupal.behaviors.someClicks = {
        attach: function(context, settings) {
            $('#whatever').click(function() {
               console.log('vamoooh');
            });
       }
    }
})(jQuery);
  • Thank you rémy! Edited my question with working corrections! – acanana Jun 18 '15 at 19:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.