Drupal Answers is a question and answer site for Drupal developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|improve this question
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 '14 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 '14 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 '14 at 2:06

Your Answer


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.