6

I am trying to do a simple ajax request when the document is ready. Along with that, I also want to provide a function that is an onclick event.

Here is my code:

(function ($) {

  Drupal.behaviors.user_alert_get_message = {
    attach: function(context, settings) {

            $.ajax({
               type: "GET",
               url: "/admin/user-alert/get-message",
               success: function(data){
                   $('div#block-user-alert-user-alert').html(data);
               }
             });

        $('div.user-alert-close a', context).click(function() {
          alert(1);
        });
    }
  };
}(jQuery));

The click function does not fire. The ajax does. What can I wrap the ajax in so it only does this on page load, or, is that assumed through attach?

I also tried an onclick on the a tag, but Firebug said the function was undefined, even when it was defined as function (function name) in the .js file.

Edit:

If you have a click event that accepts an argument, how can I pass that in?

  • Is 'div.user-alert-close a' created as a result of <code> $('div#block-user-alert-user-alert').html(data) </code> or is it already on the page? – shawngo Jul 17 '11 at 19:44
  • It's a result of that. – Kevin Jul 17 '11 at 20:35
5

As I understood it, Drupal.behaviors attach would allow the .click to fire on an element created at anytime. But just in case, I would try using .delegate(), as in

$('body').delegate('div.user-alert-close a', 'click', function() {
  alert(1);
});
0

What are Drupal Behaviors?

In short, Drupal.behaviors is a more modular and better way to implement jQuery.ready. Unlike jQuery.ready which only runs once when the DOM is ready for manipulation, Drupal.behaviors can be ran multiple times during page execution. Even better, they can be ran whenever new DOM elements are inserted into the document (i.e. AJAX driven content).

Drupal.behaviors can also override or even extend an existing behavior. So for instance, if a module behavior adds a bounce effect on all links, another module could replace that behavior with a different bounce effect.

Another added bonus of Drupal.behaviors (starting in Drupal 7), is the ability to use the drupal_add_js (PHP) or Drupal.settings.modulename (JS) and pass settings as a second parameter (the first being the context) to the behavior.

Have a look at the following resources for more information:

-3

Best practices for this, follow:

$('.yourClassElement').once('behaviorsName').click(function() {
    console.log('Cliqued');
});

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.