Last updated July 26, 2015. Created on March 29, 2010.
Edited by forestmars, Pol, Jaypan, drupalshrek. Log in to edit this page.

Drupal 7 has introduced several new techniques that allow you far greater flexibility and control in the scripts you can have on your Drupal site's pages.

Adding JavaScript

In Drupal 7, there are four primary methods of adding JavaScript to Drupal.

Method 1: Module/Theme .info file

JavaScript files can be added to a module and/or theme .info files. When adding JavaScript using this method, it will be included on every page. This allows Javascript to be aggregated in an optimal way, and is the preferred method of adding Javascript that most visitors will need on most/all pages on a typical site visit. Example:

scripts[] = somescript.js

Method 2: drupal_add_js()

JavaScript can be added in any function using drupal_add_js(). See the rest of this page and the documentation page for the various options available when calling this function. Example:

<?php
drupal_add_js
('path/to/somescript.js');
?>

Method 3: #attached

Drupal 7 makes heavy use of render arrays. Any element of a render array can have the #attached property, and this property can be used to attach JavaScript to that element. Example:

<?php
$element
['#attached']['js'][] = array(
 
'type' => 'file',
 
'data' => 'path/to/somescript.js',
);
?>

Note that when possible, this method is preferred over drupal_add_js(), as the reference to the file is cached, whereas drupal_add_js() requires a function call to add the script to the page. In some instances, such as hook_block_view(), drupal_add_js() will not be called if the block is cached, and therefore #attached must be used to ensure your code is loaded with the block.

Method 4: Libraries

Drupal Libraries provide a standardized method of adding collections of JavaScript and CSS. Libraries can, for example, be used to integrate jQuery plugins with Drupal. If you have a set of JavaScript and/or CSS that could be considered a package, it can be provided it as a library to other modules by implementing hook_library(). It can then be included by using either ['#attached']['libraries_load'] or drupal_add_library(). This is the preferred way to integrate with JavaScript and CSS which might be used by other modules.

An example of a system provided library can be found in system.module, which defines the Vertical Tabs library. This library includes one JavaScript file and one CSS file. The library is defined as follows:

<?php
function system_library() {
  ...
 
// Vertical Tabs.
 
$libraries['vertical-tabs'] = array(
   
'title' => 'Vertical Tabs',
   
'website' => 'http://drupal.org/node/323112',
   
'version' => '1.0',
   
'js' => array(
     
'misc/vertical-tabs.js' => array(),
    ),
   
'css' => array(
     
'misc/vertical-tabs.css' => array(),
    ),
  );
  ...
  return
$libraries;
}
?>

The library can then be added using one of the following methods.
drupal_add_library() example:

<?php
// Module name: system
// Library name: vertical-tabs
drupal_add_library('system', 'vertical-tabs');
?>

#attached example:

<?php
// Module name: system
// Library name: vertical-tabs
$element['#attached']['libraries_load'][] = array('system', 'vertical-tabs');
?>

Do not directly add library files

drupal_add_js() and [#attached]['js'] should not be used for JavaScript which is part of a library (as all core JavaScript libraries are). Use drupal_add_library(), or ['#attached']['libraries_load'] instead.

Weighted JavaScript

When adding JavaScript, you can add a weighted "group" value to each script so you can control the order in which JavaScript is outputted on the page. The following constants are available to be used as values when using the "group" value:

  • JS_LIBRARY: Any libraries, settings, or jQuery plugins.
  • JS_DEFAULT: Any module-layer JavaScript.
  • JS_THEME: Any theme-layer JavaScript

Groups will be added to the page in the above order. All files in the JS_LIBRARY group will be added first, followed by files in the JS_DEFAULT group, and finally files in the JS_THEME group. JavaScript files added in modules are automatically added to the JS_DEFAULT group, and JavaScript files added in themes are automatically added to the JS_THEME group.

You can also use the "weight" property to fine-tune the output order of JavaScript files. The weight will affect files that have the same 'scope', 'group', and 'every_page' levels.

drupal_add_js() example:

<?php
drupal_add_js
(
 
'jQuery(document).ready(function () { alert("Hello!"); });',
  array(
   
'type' => 'inline',
   
'scope' => 'footer',
   
'group' => JS_THEME,
   
'weight' => 5,
  )
);
?>

#attached example:

<?php
$element
['#attached']['js'][] = array(
 
'type' => 'inline',
 
'data' => 'jQuery(document).ready(function () { alert("Hello!"); });',
 
'scope' => 'footer',
 
'group' => JS_THEME,
 
'weight' => 5,
));
?>

External JavaScript

External scripts can be included as follows.
drupal_add_js() example:

<?php
drupal_add_js
('http://example.com/example.js', 'external');
?>

#attached example:

<?php
$element
['#attached']['js'][] = array(
 
'type' => 'external',
 
'data' => 'http://example.com/example.js',
);
?>

Passing values from PHP to Javascript with "Drupal.settings"

You can easily make variables from PHP available to Javascript on the front end with Drupal.settings.

drupal_add_js() example:

<?php
  drupal_add_js
(array('myModule' => array('key' => 'value')), 'setting');
?>

#attached example:

<?php
$element
['#attached']['js'][] = array(
 
'type' => 'setting',
 
'data' => array('myModule' => array('key' => 'value')),
);
?>

This will be available in Javascript as:

  if (Drupal.settings.myModule.key === 'value') {
    alert('Got it!');
  }

NB: Drupal.settings may not be available until after your javascript as been attached to the page, which can result in undefined errors if it's being immediately called.

Overriding JavaScript

hook_js_alter() allows you to modify the path referenced by one of the scripts added by core or another module. An obvious example is if you want to use a newer version of jQuery than what comes with core:

<?php
function hook_js_alter(&$javascript) {
 
$javascript['misc/jquery.js']['data'] = drupal_get_path('module', 'jquery_update') . '/jquery.js'; // Swap out jQuery to use an updated version of the library
}
?>

Behaviors

Behavior handling has changed in Drupal 7, with modules now required to explicitly define their attach handler, and optionally specify a detach handler.

Instead of the settings being a global object, settings are now passed to your handlers directly, after the context.

In Drupal 6, Drupal.behaviors was structured as follows:

Drupal.behaviors.exampleModule = function (context) {
  $('.example', context).click(function () {
    $(this).next('ul').toggle('show');
  });
}

In Drupal 7, Drupal.behaviors is structured as follows:

(function ($) {
  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
      $('.example', context).click(function () {
        $(this).next('ul').toggle('show');
      });
    }
  };
}(jQuery));

These behaviors are instigated as you declare them in JavaScript so to clarify, there is no need for defining behaviors within a theme's or module's PHP file.

Additional References

Lullabot published a comprehensive article regarding Drupal behaviors.

Using jQuery

jQuery is now namespaced to avoid conflicts with other Javascript libraries such as Prototype. All your code that expects to use jQuery as $ should be wrapped in an outer context like so.

(function ($) {
  // All your code here
})(jQuery);

If you don't, you may see the error Uncaught TypeError: Property '$' of object [object DOMWindow] is not a function or similar.

jQuery $.once()

Drupal.behaviors will often be called multiple times on a page. For example, every time a form performs some Ajax operation, all Drupal behaviors will be executed again after page load, in order to attach any relevant JavaScript to the newly loaded elements. This can have the undesired affect of applying JavaScript to elements each time Drupal behaviors are executed, resulting in the same code being applied multiple times. To ensure that the JavaScript is applied only once, we can use the jQuery $.once() function. This function will ensure that the code inside the function is not executed if it has already been executed for the given element.

Using jQuery $.once() (integrated into D7 core), the developer experience of applying these effects is improved. Note that there is also the $.removeOnce() method that will only take effect on elements that have already applied the behaviors.

Drupal.behaviors.mybehavior = {
  attach: function (context, settings) {
    $('#some_element', context).once('mybehavior', function () {
      // Code here will only be applied to $('#some_element')
      // a single time.
    });
  }
};

For best-practice examples, it's helpful to look at (comparatively) simple examples such as misc/collapse.js to see how it's done.

Looking for support? Visit the Drupal.org forums, or join #drupal-support in IRC.

Comments

mradcliffe’s picture

The settings object behaves similarly to Drupal 6 with the exception that it is not within the Drupal namespace.

So "Drupal.settings.blah.setting" becomes "settings.blah.setting".

Jaypan’s picture

So "Drupal.settings.blah.setting" becomes "settings.blah.setting".

This quote is incorrect. It will be Drupal.settings.blah.setting.

drupik’s picture

This qoute is correct, you can access setting with Drupal.settings.blah.setting or inside the function settings.blah.setting.

Jaypan’s picture

You are opening yourself up to errors with that, as any other element that is found with a settings element may be found before Drupal.settings. It's also inefficient as it has to search for settings.

Again the correct way to do this is to use Drupal.settings.

drupik’s picture

Not true, correct way: http://drupal.org/node/224333#local_settings_behaviors. What errors do you mean? You are opening yourself up for errors like this: http://drupal.org/node/360081

Jaypan’s picture

Sorry, the confusion has been on my part, as I didn't properly look at the example code. I have been adding my JS as follows:

Drupal.behaviors.myModule = {
  attach: function () {
    // some code
  }
};

In which case, Drupal.settings is the correct way to access the settings object. However, the examples are using this code:

Drupal.behaviors.myModule = {
  attach: function (context, settings) {
    // some code
  }
};

In this case, it's better to access the settings object directly, as you and the poster above have pointed out. Drupal.settings will also work, but calling settings directly is preferable.

Danny Englander’s picture

I solved part of this in trying to convert from a Drupal 6 theme to Drupal 7. I have a nice little JQuery drop down menu function that no longer worked in Drupal 7.

My old Drupal 6 code was:

Drupal.behaviors.MyThemeBehavior = function(context) {

  jQuery('#navigation ul').superfish({
    animation: { opacity: 'show', height:'show' },
    easing: 'swing',
    speed: 250,
    autoArrows:  false,
    dropShadows: false /* Needed for IE */
  });

};

Now in Drupal 7, based on the code sample on this page, I did this:

(function ($) {

  Drupal.behaviors.MyTheme = {
    attach: function(context, settings) {
      $('#navigation ul', context).superfish(function () {
    
      });
    }
  };

})(jQuery);

The only thing I can't figure out how to do it put the animation, easing and speed code back in but at least the menus are working to a degree.

Update
Finally found a fix to this:

(function ($) {

Drupal.behaviors.naturalessenceTheme = {

attach: function(context, settings) {
$('#navigation ul', context).superfish({

animation: { opacity: 'show', height:'show' },
speed: 250,
autoArrows: false,
dropShadows: false /* Needed for IE */

});

}
};

})(jQuery);

a great place for frogs’s picture

I found this page very helpful but am still having trouble getting jQuery to work in D7. I'm not a programmer but I can get around html and CSS well enough. I've used Drupal for a few years now, am comfortable manipulating themes although I bawk at writing my own modules. A few questions please.

I've downloaded the jq4dat theme, the template.php file uses drupal_add_library in the preprocess_page function. I've added another one (for tabs) and the javascript and css from misc/ui is now included in the html source. I've updated the .info and my script (from http://flowplayer.org/tools/demos/tabs/index.html), appropriately wrapped is also being called. It looks like this..

(function ($) {

$("ul.tabs").tabs("div.panes > div");

})(jQuery);

I've also added the CSS as described at the flowplayer site and included the html in my node content.

Do I need any drupal behaviours? Is my script OK? Something is missing.

I'd love to get this happening and would be happy to help with the documentation once I know how to work it.

Thanks

Claus Weymann’s picture

I finally found a working example here
http://www.jromero.me/blog/jquery-ui-drupal
hope it helps with your problem as well

rockoyster’s picture

Sorry if this is a totally dumb question but can someone explain where the drupal.add.js needs to be inserted. Is it in template.php or what?

I have been playing with the Bluemasters theme and it includes a script on the front page by incorrectly adding the script at the top of the page--front.tpl.php. It works but the source code ends up with two body tags. Erk! I could copy html.tpl.php and add the script there but there has to be a better way. I have also tried adding the scripts [] = js/bluemasters.js entry to the .info file but this doesn't seem to include anything.

Any suggestions?

rockoyster’s picture

I figured out to put the drupal_add_js at the top of page--front.tpl.php. That works fine. Still can't work out how to include script via .info file though.

RobW’s picture

drupal_add_js() can go in template files and even in php fields in content, anywhere that php is evaluated. That said, it's best/neatest to put them in a function (usually preprocess) in your template.php, or in a module if that's what is providing the content that needs the javascript.

An example of a preprocess function would be something like this:

<?php
//This is preprocessing the html on a theme named "my_theme", checking if a particular class is applied to the body, and adding js if it is.
function my_theme_preprocess_html(&$variables) {

 
//Checks if the required string is in the classes array. Here I'm looking for page-my-view, which is the class that appears in the body tag on pages created by a view called My View.
 
if ((in_array('page-my-view', $variables['classes_array']))) {

 
//Set up the options for the drupal_add_js() function See the api docs for explanation.
 
$options = array(
   
'group' => JS_LIBRARY,
   
'type' => 'external'
 
);
 
//here's the function itself.
 
drupal_add_js('http://ajax.microsoft.com/ajax/jquery.cycle/2.88/jquery.cycle.min.js', $options);

 
//Add another js file. First I'll make some changes to the $options (tell Drupal it's an internal file). I want to keep the type  as JS_LIBRARY, so I leave it as defined above.
 
$options = array(
   
'type' => 'file'
 
);
 
//..and use the function again.
 
drupal_add_js(drupal_get_path('theme', 'my_theme'). '/js/script.js', $options);
  }
 
}
?>

That would give me two files, http://ajax.microsoft.com/ajax/jquery.cycle/2.88/jquery.cycle.min.js and sites/all/my_theme/js/script.js, added only to pages where the body class contains "page-my-view". You might use similar code to preprocess your node and add js based on node type, or check a field value and add js accordingly.

Kristina Katalinic’s picture

Hi, I am a non coder and have ported a theme from D6 to D7. Theme is absolutely beautiful but it seems it was never built for speed because none of my css or js were aggregating when compression is enabled in performance. I sorted out most of the .css but this piece of jquery included in my htm.tpl.php is still giving me headaches <script src="http://code.jquery.com/jquery-1.4.4.js"></script> because I cannot aggregate it and its taking on average 2s to load from external source. Seeing that jquery 1.4.4 is already included in D7 I'd prefer to use drupal_add_js to include jquery 1.4.4 from system libraries.
Would you please be so kind to post an example on how to do that because all examples i found so far seem to be related to adding .js files included in the theme folder or from external source but none deal with doing it from the system itself? Thanks in advance

Brisbane Web Design, Development and SEO consulting services.
www.webmar.com.au

Danny Englander’s picture

JQuery 1.4.4 is already included with Drupal 7 so I am not sure why you are trying to add it again in html.tpl.php? Since it's included, you merely need to use the methods as outlined on this page to call specific custom JQuery code and functions. I also just wrote a blog post on this on my website. (linked from my profile or sig).

truyenle’s picture

Thank, this work for me. Easy to understand and implement.

perumal.karthi’s picture

m4olivei’s picture

I'd like to see some explanation around jquery.once.js plugin. All of the core Javascript that I've looked at so far makes use of this plugin. I'd like to see an explanation from someone in the know as to why this is used everywhere and what it replaces from Drupal 6.

I'll take a swing at an explanation here, I'd love to hear comments. In my own experimentation I gather that its a way to ensure that you only run JS code on a set of matched elements once, hence the plugins name. The plugin works by removing elements from the matched set with a class that labels the element as having been previously processed. jQuery each() is run on the remaining elements passing in the function that was passed as the second argument to jQuery once(). Thus, introducing jquery.once.js into core gives us a standardized was to ensure that our Drupal behaviors are not run more than once on a set of matched elements, which could for example set the same click handler twice.

Matt

gagarine’s picture

I add some text about that in the doc.. You can also check http://drupal.org/node/224333#jquery_once

------
cloud33.com

m4olivei’s picture

That's great thanks!

AgaPe’s picture

Hi,
i have a working code for views exposed filter. when submit button is clicked its not reloade. but the code submits the form without ajax. i have read that behaviors should help with that but not working.
Am i missing something?

(function($){

  Drupal.behaviors.dl = {
    attach: function(context, settings) {
      $(".picture-submit", context).click(function() {
        $("#views-exposed-form-media-updates-list-page-media-updates").submit();
      });
    }
  };

})(jQuery);

aendrew’s picture

I'm trying to do the same thing -- did you ever have any success with this?

Ændrew Rininsland
News Developer and polynerd
http://www.aendrew.com

mjcarter’s picture

You need to write the function with the event parameter,

.click(function(event)

then add

event.preventDefault();

to the function. This prevents the submit button from doing it's default action.

cwestin’s picture

Detailed description of the problem here: http://drupal.stackexchange.com/questions/4401/how-do-get-a-body-onload-... , includes all the details of how I built the module, which is just a JavaScript file.

Basically, I see my .js file loaded on the page (there's a script tag when I View Source), but the attach() I defined doesn't seem to do anything. I tried adding a $(body).ready() to a Drupal.behavior as described above to do what I need, but it never fires. The StackExchange entry above has links to the source.

dannyjohnson1’s picture

I want to implement this sticky-scroll jquery plug-in on a drupal 7 theme to both sidebars.

https://github.com/Forrst/sap/blob/master/README.md

  1. I've added the jquery.sap.js to my .info file and I can see when viewing source its showing up.
  2. I've changed the "sap-shimy-shim" to "sidebar"
  3. Now, I must apply Sap to an element in the DOM by simply calling $(selector).sap()

I have no idea where/how to do #3. I'm think it has something to do with Drupal.behaviors.??

I'm comfortable with drupal theming using css but new to jquery.

Help!

RobW’s picture

In the .js that you're calling with you info file, attach anything you'd normally put in a document.ready() to Drupal behaviors. Example:

(function ($) {
Drupal.behaviors.naturalessenceTheme = {
attach: function(context, settings) {

/*Add your js code here*/

}
};
})(jQuery);

bburg’s picture

Thank you! Many folks, like me, are used to just always wrapping js in document.ready and then spend much too long wondering why their Drupal behavior isn't firing.

lgammo’s picture

Does this mean that a js file added in an .info file is actually loaded for every page requested from the site and not just on pages that contain the module generated content?

In other words, if I added a file called test.js to the test.info file. Will the test.js file be loaded into a page that has nothing to do with the test module? For example, while displaying any other node type?

Thank you,

--
Louay Gammo

aasarava’s picture

The documentation above suggests wrapping code like so:

(function ($) {
  // All your code here
}(jQuery));

But typically the arrangement of the closing parentheses is like this:

(function ($) {
  // All your code here
})(jQuery);  //see the difference here, jQuery is on outside

Is there a semantic difference? Should the documentation be updated?

grossmann’s picture

I wondered about that too. Which is the correct way now?
grossmann-mcs

grossmann

arnoldbird’s picture

Correct closing:
})(jQuery);
Fixed now in the article above.

graceman9’s picture

and finally... any difference?

ajankovic’s picture

Both versions are doing the same thing. Just use the version which you prefer.

Jeff Burnz’s picture

Using the hook_js_alter() example for vertical-tabs.js gave me undefined index errors for type and scope, I had to define the defaults:

<?php
function adaptivetheme_js_alter(&$javascript) {
 
$file = drupal_get_path('theme', 'adaptivetheme') . '/js/vertical-tabs.js';
 
$javascript['misc/vertical-tabs.js'] = drupal_js_defaults($file);
}
?>
arnoldbird’s picture

Unfortunately, the "attach" statements cause firebug to complain about a missing colon. Does anyone have a fix for that?

Danny Englander’s picture

I just ran into a case for Drupal 7 where I needed to fire off JQuery after an Ajax event on my pages. I came up with this code and it worked really well. Note the $('.mydiv').ajaxComplete(function() {

(function ($) {
    //add drupal 7 code
    Drupal.behaviors.MyfunctionTheme = {
        attach: function(context, settings) {
    //end drupal 7 calls

            //Tell JQuery that there's an Ajax event first
            $('.mydiv').ajaxComplete(function() {
        // now your actual code
               $(this).remove() // or whatever code you need to execute
            });
        }}})
(jQuery);

kanzer’s picture

Hello good day

Is this going into my template.php?
I explain
I have a list of songs with views
This view has a filter block that recharge the song list
every song has a class. add-music that adds the song to the playlist of JPlayer
works well but it is reloaded each ajax longer works

I know I'm an ignoramus
well look what I put on the block where you JPlayer:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript" src="http://jplayer.org/latest/js/jquery.jplayer.min.js"></script>
<script type="text/javascript" src="http://jplayer.org/latest/js/jplayer.playlist.min.js"></script>
<link href="http://red.comppa.com/sites/all/modules/jplayer/theme/jplayer.blue.monday.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
//<![CDATA[
$(document).ready(function(){

var myPlaylist = new jPlayerPlaylist({
jPlayer: "#jquery_jplayer_N",
cssSelectorAncestor: "#jp_container_N"
}, [
{
title:"El pescador",
artist:"40",
mp3:"http://mypage.com/sites/default/files/audios/EL%20Pescador.mp3",
}
], {
playlistOptions: {
enableRemoveControls: true
},
swfPath: "../js",
supplied: "oga, mp3"
});

// Click handlers for jPlayerPlaylist method demo

// Audio mix playlist
        $('.add-music').click(
function() {
  myPlaylist.add({
    title: $(this).attr('data-title'),

    artist: $(this).attr('data-artist'),
    mp3: $(this).attr('href')
  });
  return false; // Not required when href omitted.
});

// The remove commands

$("#playlist-remove").click(function() {
myPlaylist.remove();
});

$("#playlist-remove--2").click(function() {
myPlaylist.remove(-2);
});
$("#playlist-remove--1").click(function() {
myPlaylist.remove(-1);
});
$("#playlist-remove-0").click(function() {
myPlaylist.remove(0);
});
$("#playlist-remove-1").click(function() {
myPlaylist.remove(1);
});
$("#playlist-remove-2").click(function() {
myPlaylist.remove(2);
});

// The shuffle commands

$("#playlist-shuffle").click(function() {
myPlaylist.shuffle();
});

$("#playlist-shuffle-false").click(function() {
myPlaylist.shuffle(false);
});
$("#playlist-shuffle-true").click(function() {
myPlaylist.shuffle(true);
});

// The select commands

$("#playlist-select--2").click(function() {
myPlaylist.select(-2);
});
$("#playlist-select--1").click(function() {
myPlaylist.select(-1);
});
$("#playlist-select-0").click(function() {
myPlaylist.select(0);
});
$("#playlist-select-1").click(function() {
myPlaylist.select(1);
});
$("#playlist-select-2").click(function() {
myPlaylist.select(2);
});

// The next/previous commands

$("#playlist-next").click(function() {
myPlaylist.next();
});
$("#playlist-previous").click(function() {
myPlaylist.previous();
});

// The play commands

$("#playlist-play").click(function() {
myPlaylist.play();
});

$("#playlist-play--2").click(function() {
myPlaylist.play(-2);
});
$("#playlist-play--1").click(function() {
myPlaylist.play(-1);
});
$("#playlist-play-0").click(function() {
myPlaylist.play(0);
});
$("#playlist-play-1").click(function() {
myPlaylist.play(1);
});
$("#playlist-play-2").click(function() {
myPlaylist.play(2);
});

// The pause command

$("#playlist-pause").click(function() {
myPlaylist.pause();
});

// Changing the playlist options

// Option: autoPlay

$("#playlist-option-autoPlay-true").click(function() {
myPlaylist.option("autoPlay", true);
});
$("#playlist-option-autoPlay-false").click(function() {
myPlaylist.option("autoPlay", false);
});

// Option: enableRemoveControls

$("#playlist-option-enableRemoveControls-true").click(function() {
myPlaylist.option("enableRemoveControls", true);
});
$("#playlist-option-enableRemoveControls-false").click(function() {
myPlaylist.option("enableRemoveControls", false);
});

// Option: displayTime

$("#playlist-option-displayTime-0").click(function() {
myPlaylist.option("displayTime", 0);
});
$("#playlist-option-displayTime-fast").click(function() {
myPlaylist.option("displayTime", "fast");
});
$("#playlist-option-displayTime-slow").click(function() {
myPlaylist.option("displayTime", "slow");
});
$("#playlist-option-displayTime-2000").click(function() {
myPlaylist.option("displayTime", 2000);
});

// Option: addTime

$("#playlist-option-addTime-0").click(function() {
myPlaylist.option("addTime", 0);
});
$("#playlist-option-addTime-fast").click(function() {
myPlaylist.option("addTime", "fast");
});
$("#playlist-option-addTime-slow").click(function() {
myPlaylist.option("addTime", "slow");
});
$("#playlist-option-addTime-2000").click(function() {
myPlaylist.option("addTime", 2000);
});

// Option: removeTime

$("#playlist-option-removeTime-0").click(function() {
myPlaylist.option("removeTime", 0);
});
$("#playlist-option-removeTime-fast").click(function() {
myPlaylist.option("removeTime", "fast");
});
$("#playlist-option-removeTime-slow").click(function() {
myPlaylist.option("removeTime", "slow");
});
$("#playlist-option-removeTime-2000").click(function() {
myPlaylist.option("removeTime", 2000);
});

// Option: shuffleTime

$("#playlist-option-shuffleTime-0").click(function() {
myPlaylist.option("shuffleTime", 0);
});
$("#playlist-option-shuffleTime-fast").click(function() {
myPlaylist.option("shuffleTime", "fast");
});
$("#playlist-option-shuffleTime-slow").click(function() {
myPlaylist.option("shuffleTime", "slow");
});
$("#playlist-option-shuffleTime-2000").click(function() {
myPlaylist.option("shuffleTime", 2000);
});

// AVOID COMMANDS

$("#playlist-avoid-1").click(function() {
myPlaylist.remove(2); // Removes the 3rd item
myPlaylist.remove(3); // Ignored unless removeTime=0: Where it removes the 4th item, which was originally the 5th item.
});

$("#jplayer_inspector_1").jPlayerInspector({jPlayer:$("#jquery_jplayer_N")});
});
//]]>
</script>
<div id="jp_container_N" class="jp-video jp-video-270p">
<div class="jp-type-playlist">
<div id="jquery_jplayer_N" class="jp-jplayer"></div>
<div class="jp-gui">
<div class="jp-interface">
<div class="jp-progress">
<div class="jp-seek-bar">
<div class="jp-play-bar"></div>
</div>
</div>
<div class="jp-current-time"></div>
<div class="jp-duration"></div>
<div class="jp-title">
<ul>
<li></li>
</ul>
</div>
<div class="jp-controls-holder">
<ul class="jp-controls">
<li><a href="javascript:;" class="jp-previous" tabindex="1">previous</a></li>
<li><a href="javascript:;" class="jp-play" tabindex="1">play</a></li>
<li><a href="javascript:;" class="jp-pause" tabindex="1">pause</a></li>
<li><a href="javascript:;" class="jp-next" tabindex="1">next</a></li>
<li><a href="javascript:;" class="jp-stop" tabindex="1">stop</a></li>
<li><a href="javascript:;" class="jp-mute" tabindex="1" title="mute">mute</a></li>
<li><a href="javascript:;" class="jp-unmute" tabindex="1" title="unmute">unmute</a></li>
<li><a href="javascript:;" class="jp-volume-max" tabindex="1" title="max volume">max volume</a></li>
</ul>
<div class="jp-volume-bar">
<div class="jp-volume-bar-value"></div>
</div>
<ul class="jp-toggles">
<li><a href="javascript:;" class="jp-full-screen" tabindex="1" title="full screen">full screen</a></li>
<li><a href="javascript:;" class="jp-restore-screen" tabindex="1" title="restore screen">restore screen</a></li>
<li><a href="javascript:;" class="jp-shuffle" tabindex="1" title="shuffle">shuffle</a></li>
<li><a href="javascript:;" class="jp-shuffle-off" tabindex="1" title="shuffle off">shuffle off</a></li>
<li><a href="javascript:;" class="jp-repeat" tabindex="1" title="repeat">repeat</a></li>
<li><a href="javascript:;" class="jp-repeat-off" tabindex="1" title="repeat off">repeat off</a></li>
</ul>
</div>
</div>
</div>
<div class="jp-playlist">
<ul>
<!-- The method Playlist.displayPlaylist() uses this unordered list -->
<li></li>
</ul>
</div>
<div class="jp-no-solution">
<span>Update Required</span>
To play the media you will need to either update your browser to a recent version or update your <a href="http://get.adobe.com/flashplayer/" target="_blank">Flash plugin</a>.
</div>
</div>
</div>

Please ask help understanding how to implement this code in drupal
that does not conflict with superfish etc ...

greetz

ranelpadon’s picture

Thanks @Danny Englander for this valuable tip. It helped me solve my issue with Colorbox Node's custom behaviors. I've used jQuery.once() inside of attach() but it executes too early if the request took some time to finish, which makes the jQuery selector to be applied to empty elements. jQuery.ajaxComplete() event makes it possible to define the precise timing when to run jQuery.once().

Norman.Schmidt’s picture

Hey, I have tried the described:

"scripts[] = somescript.js" ... in the .info file of my used theme.

Anyhow the system does always add a "?lvdcsh" to the script files link and it seems that the script does not work correct because of that, am I right?
Here is the scripts link:
<script type="text/javascript" src="http://onvedi.de/sites/all/themes/simpleclean/js/googledfp.js?lvdcsh"></script>

Any suggestion?

TwoD’s picture

That part of the URL, the querystring, should not affect your script at all.
It's added so Drupal can change 'lvdcsh' into something else when you clear the Drupal caches. Changing the URL will make the browser think it's a new script, and reload it from the server instead of fetching it from its own cache. That ensures your visitors get the latest version if you've modified something.

Any script added to the .info file of an active module or theme will be included on all pages. If it's not working, check the browser's JavaScript console for errors, or contact the person who wrote the script so they can debug it.

hongquan’s picture

If the setting is pass to JavaScript handler directly:
handler(context, setting)
how to pass that setting from PHP code?
Because the setting passed via drupal_add_js will go to global Drupal.setting.

ilalaina’s picture

I just don't want to use jquery ui on the front end of my site, how can i prevent Drupal to load it to minimise page weight ?

Thanks,
Ilalaina.

RobW’s picture

You can do some preprocessing, or use a module like http://drupal.org/project/blackwhite.

bianchi’s picture

Guys,
What can I do if javascript is off in the browser ?
Degrade gracefully ??

Any ideas ?

Cheers
Thanks mate

AddressMcGee’s picture

all this to add a little js file? kinda ridiculous.

Jaypan’s picture

No, not all that to add a little js file. All that to create a powerful javascript framework that can be used to make javascript applications and more.

You can also add js files with it.

bassemc’s picture

If you need to add a javascript inline just to specific nodes (Drupal 7.x) (I have not tried it on Drupal 6.x), like for example adding an AmMap or AmChart, where you do not necessarily want it to load whend your theme or module loads you can do the following:

1) Save your <script>...</script> in a MyScript.js file which you have created and upload it somewhere in like sites/all/scripts/MyScript.js
2) In the node body where you want to include the script, select for text format and put in the following code

<?php
 
include('sites/all/scripts/MyScript.js');
?>

[Example: including an AmMap script]

In this example the Myscript.js file is unemployement.js and it is located in sites/all/scripts/ammap/unemployment.js

contents of unemployment.js:

<script src="../sites/all/scripts/ammap/ammap.js" type="text/javascript"></script>
<script src="../sites/all/scripts/ammap/LebanonHigh.js" type="text/javascript"></script>
   <script type="text/javascript">
var map;
var icon= "M21.25,8.375V28h6.5V8.375H21.25zM12.25,28h6.5V4.125h-6.5V28zM3.25,28h6.5V12.625h-6.5V28z";

AmCharts.ready(function() { //........etc continue your code....

and then call the script from within the node:

<?php
 
include('sites/all/scripts/ammap/unemployment.js');
?>

In this case, where you have other scripts being called by unemployment.js, make sure you have them uploaded on your server, the ones being loaded by the above script [unemployment.js] are: ammap.js and LebanonHigh.js, and i have put them both in sites/all/scripts/ammap/. and in my script unemployment.js i have loaded them with <script src="sites/all/scripts/ammap/ammap.js" type="text/javascript"></script>, specifying their location on the server.

This method works well when you are adding visual elements to specific nodes and you do not want the scripts to load on all pages or on the theme.
Reference: http://goodkarmahost.com/topics/tech-help/adding-inline-javascript-to-a-...

--
Bassem Sheet
Beirut, Lebanon

Kroinghero1’s picture

In drupal 6, it was quite easy to add Javascript by adding
in the interface, for example in a block, and then set the
filter on Raw filter, not filtering anything.

However, in Drupal 7, I am still confused. Now
I added the javascript in a .js-file in here, naming it example.js:
www.domain.com/sites/all/themes/garland/js/example.js

Also, I added the following in the info-file of the theme-folder:
scripts[] = somescript.js

Now I want to call that js-file in node.tpl.php via

<?php
  drupal_add_js
(array('myModule' => array('key' => 'value')), 'setting');
?>

but how shall I do that? This way or that way, it won´t work. Thank you so much for your help!!!!

Account manager at globalprotec

Jaypan’s picture

First off, you shouldn't actually be making changes to the garland theme, as your changes will be overwritten when you update Drupal. Instead, you should make a sub-theme of Garland, and make your changes there. You can see how to make a sub-theme here: https://www.drupal.org/node/2324377

Next, by adding scripts[] = example.js to your info file, example.js will be included on every page load. If you then want to add some settings, you should do this in the relevant preprocess function. For example, you want your JS setting to be part of node.tpl.php, so you should add the following in hook_preprocess_node():

<?php
function THEME_KEY_preprocess_node(&$vars)
{
 
drupal_add_js(array('myModule' => array('key' => 'value')), 'setting');
}
?>

If you have more questions on this however, you should probably start a forum topic on the matter, and link to your forum topic of you want.

Tuong’s picture

I'm trying to add some custom jquery code to my theme. I used the code below :

function($) {
Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {
    //code starts
    $("body").click(function() {
      alert("Hello World");
    });
    //code ends

  }
};
})(jQuery);

The jquery file is loaded with the script but nothing happens on my page, any help ?

Sent from my cách làm sữa chua using drupal community

Jaypan’s picture

This:
function($) {
Should be this:
(function($) {