How To Add jQuery to Drupal Theme

Categories: 

 Resource: https://www.drupal.org/docs/7/theming/working-with-javascript-and-jquery

JavaScript files can be added to a theme's .info file using the scripts tag. For example, to add the script main.js to every page on a Drupal site add the following to the theme's .info file.

  1. Add the following line to your .info file

                   scripts[ ]= scripts/main.js

            Put your jQuery file named main.js into folder called scripts in your theme folder.
            Clear the theme cache to take effect.

  1. Drupal 7 comes with jQuery 1.4.4 and jQuery UI 1.8.7.
  • Install jQuery Update module to use more recent versions of jQuery.
  • On the configuration page, choose the version of jQuery that you want to use under Theme Overrides. Eg. 1.7
  • Under the Performance tab, choose Development(uncompressed) for use during development.

 

  1. For use during development, in Drupal admin pages, under the Configuration > Development > Performance

 
         Uncheck Compress cached pages
         Uncheck Aggregate and compress CSS files
         Uncheck Aggregate Javascript files.
 

  1. It's best practice to wrap your code in a closure. A closure is nothing more than a function that helps limit the scope of variables so you don't accidentally overwrite global variables.

 
          Add this code to jQuery code main.js for a closure

                          jQuery(document).ready(function($)) {
                                     // code that uses jQuery’s $ can follow here
                            });