How to add jQuery in certain pages on Drupal

  • 0
Sometimes we need to attach a js script on specific pages on Drupal, in this post i will show you how to do that. Firstly we need to know the query string so we can check it against the URL you could use this $_GET['q'] == 'path_to_your_page' see the following example :

if ($_GET['q'] == 'node/add/vacation' 
|| $_GET['q'] == 'node/add/time-record' 
|| $_GET['q'] == 'node/add/mission' ) {
  drupal_add_js(drupal_get_path('module', 'my_module') . '/auto_titles.js');
}

Now you need to get the path of the current URL by using Java script -> "var url = window.location" Putting it all together:

$(document).ready(function(){
  comingUrl = window.location; // get the URL
  host = window.location.host; // get the host
  drupalPath = Drupal.settings.basePath; 
  
  desiredUrl = 'http://' + host + drupalPath;
  vacation = desiredUrl + 'en/node/add/vacation';
  timeRecord = desiredUrl + 'en/node/add/time-record';
  mission = desiredUrl + 'en/node/add/mission';
  
  //alert(vacation);

  if (comingUrl == vacation) { // if true the following line will be executed only in "en/node/add/vacation" page
    $(".breadcrumb").append("something");
  } else if (comingUrl == timeRecord){
    $(".breadcrumb").append("something");
  } else if (comingUrl == mission){
    $(".breadcrumb").append("something");
  }
  
});
I hope you find this as useful as I have.