In one of the previous posts I had discusses about this interesting Drupal module - Asset Injector which allows us to easily add CSS and JavaScript to our Drupal setup.
This post discusses about how you can add jQuery code to the same.
You need to take the following steps:
- Go to Assets Injector > Add Js Injector.
- Give it some label: lets say "test"
- Here you need to add your jQuery code.
- The important point is that adding jQuery code directly will not work. It needs to be placed inside the following piece of code:
(function($) {
Drupal.behaviors.myBehavior = {
attach: function (context, settings) {
// code goes here
}
};
})(jQuery);
- You can read more about the same at: https://www.drupal.org/docs/drupal-apis/javascript-api/javascript-api-overview and https://drupal.stackexchange.com/questions/249895/how-do-i-know-if-js-injector-is-applying-script-correctly-to-page
- Make sure to set where the Code can be executed i.e. content type, user role etc.
- Also in advanced settings select "Requires jQuery"
- Save you code and test it at the desired location.
-
Example: Find out the class of image which you want to fade in or out with moverenter and mouse out and set the selector accordingly.
(function($) {
Drupal.behaviors.myBehavior = {
attach: function (context, settings) {
// Your jQuery Code starts
$("img.class").on({
mouseenter: function() { $(this).fadeTo(500, 0.5); },
mouseleave: function() { $(this).fadeTo(500, 1); }
});
// Your jQuery Code Ends
}
};
})(jQuery);
Enjoy
Add new comment