logo

Palette - Make it Colorful🎨

Palette - Visual Page Builder, no design degree required.

Live Demo Download Palette

Scroll

Drupal and jQuery. Lesson 1. Connecting a file with jQuery.

16/04/2025, by Ivan

jQuery is a very handy tool when you need to hide something, modify it, move it, insert it nicely, and disappear. Very, very convenient and very simple. Let's connect a JavaScript file. To attach files to a theme, we use the `.info` file in your theme. To include the file, add the following line to your theme's `.info` file:

scripts[] = js/custom.js

where `js/custom.js` is the path to the JavaScript file in your theme.

Next, you need to define jQuery code execution after the page loads. For Drupal 6, this is sufficient:

$(document).ready(function(){
  //jQuery code
});

However, in Drupal 7 jQuery operates in noConflict mode, which allows you to also connect libraries like Mootools. So in Drupal 7 we use this approach:

(function($){
  $(document).ready(function(){
    //jQuery code
  });
})(jQuery);

But the best practice is to use behaviors:

(function ($) {
  Drupal.behaviors.myModuleBehavior = {
    attach: function (context, settings) {
      // Write your JavaScript code here
    }
  };
})(jQuery);

For more details on behaviors, read this article:

8.8. Working with JavaScript/jQuery in Drupal 8: What are behaviors?