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


1 Answer 1


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>');
  • Wow, that was much simpler than I thought it would be. Thank you @Clive.
    – Citricguy
    Commented Mar 29, 2014 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
    Commented Mar 29, 2014 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
    Commented Mar 29, 2014 at 2:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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