Adding jQuery code to Drupal via Asset injector.


Drupal Asset injector jQuery


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:

  1. Go to Assets Injector > Add Js Injector.
  2. Give it some label: lets say "test"
  3. Here you need to add your jQuery code. 
  4. The important point is that adding jQuery code directly will not work. It needs to be placed inside the following piece of code:
    1. (function($) {
      Drupal.behaviors.myBehavior = {  
       attach: function (context, settings) { 
        //  code goes here 
       }
      }; 
      })(jQuery);
  5. 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 
  6. Make sure to set where the Code can be executed i.e. content type, user role etc.
  7. Also in advanced settings select "Requires jQuery"
  8. Save you code and test it at the desired location.
  9. 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

 

Main category

Add new comment

Filtered HTML

  • Web page addresses and email addresses turn into links automatically.
  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
CAPTCHA
Enter the characters shown in the image.
Are you a robot?
Address

OpenSourceCook.in
"Natraj"  Bungalow,
Colony No.7,  Sr.No. 38.
(Lane Behind Sai Baba Mandir)
Kale Borate Nagar, Hadapsar,
Pune - 411028.
Get Directions