Take the 2-minute tour ×
Drupal Answers is a question and answer site for Drupal developers and administrators. It's 100% free, no registration required.

Using Drupal 7's implementation of jQuery and Drupal.behaviors, how can I get some of my jQuery to run only once when the page is initially loaded, and the rest to run when the page is loaded AND during AJAX callbacks.

How can I prevent ajax callbacks from triggering certain parts of my Drupal.behaviors?

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

            //I want to run this only during the first page load.
            jQuery('#edit-message').after('<div>Do Once</div>');

            //I want this to run during first load and during each ajax callback.
            jQuery('#edit-message').after('<div>Do Every Time</div>');
        }
    }

})(jQuery);
share|improve this question
add comment

1 Answer 1

up vote 2 down vote accepted

This'll do it:

var msg = $('#edit-message');
msg.once('fsrevs_user', function() {
  msg.after('<div>Do Once</div>');
});

msg.after('<div>Do Every Time</div>');
share|improve this answer
    
Wow, that was much simpler than I thought it would be. Thank you @Clive. –  Citricguy Mar 29 at 2:01
    
No worries :) once() is a Drupal thing but I'd guess it's just a really simple wrapper. You can do the same thing in one line with normal jQuery: msg.not('.processed').addClass('processed').each(function() { ... }); –  Clive Mar 29 at 2:04
    
I was wondering why .once() was showing up as undefined in my editor. Makes sense that it is a wrapper. Thank you for the jQuery there as well, that will be handy in other places as well. –  Citricguy Mar 29 at 2:06
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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