Tell me more ×
Drupal Answers is a question and answer site for Drupal developers and administrators. It's 100% free, no registration required.

I'm currently developing a JavaScript script that runs on an administration page. I read up on the changes made in Drupal 7, namely the move from document.ready() to its own jQuery function. However, the following script doesn't work.

(function ($) {
  console.log('hello');
  $('#edit-apiusername').append('test');
})(jQuery);

console.log() is firing and I can see the output, but the simple append doesn't work. The field ID is correct.
I am not sure what I'm missing here, but I suspect it has to do with the way I'm referencing the object. Looking at Views 3 JavaScript code, I can see it's done in a similar way.

share|improve this question
If you console.log($('#edit-apiusername')); does it output the object, ie is the element being found on the page by jQuery? – budda Mar 9 '11 at 0:33
Even with Drupal 6 you were supposed to use the Drupal behaviors, instead of document.ready. What you are reporting is not specific to Drupal 7. – kiamlaluno Mar 9 '11 at 12:32

3 Answers

up vote 27 down vote accepted

I think you misunderstood the changes.

JavaScript code should be wrapped in (function ($) { ... })(jQuery); to allow usage of $ as shortcut to jQuery. This is to allow jQuery to play nicely with other libraries. In this function, you still have to wait for the DOM to be loaded if you want to alter it. That's what wrapping your code in jQuery.ready(function(){ ... }) does.

But instead of using jQuery.ready(function(){ ... }), you should use behaviors to let Drupal's JavaScript knows that your code wants to process anything added (or removed) from the DOM.

(function ($) {
  Drupal.behaviors.exampleModule = {
    attach: function(context, settings) {
      $(context).find('#edit-apiusername').append('test');
    }
  }
})(jQuery);
share|improve this answer

This video from DrupalCon Chicago is worth watching: Drupal 7 JavaScript for Developers

share|improve this answer

You might also consider aliasing the whole jQuery object to another variable of your choice, as in:

$j = jQuery.noConflict();

You would put this outside of the ready statement to leave it accessible outside of the encapsulation.

share|improve this answer

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.