Skip to content

Instantly share code, notes, and snippets.

@davidjguru
Last active January 1, 2021 15:20
Show Gist options
  • Save davidjguru/d1df8edca861258b55b72c8659fb88a7 to your computer and use it in GitHub Desktop.
Save davidjguru/d1df8edca861258b55b72c8659fb88a7 to your computer and use it in GitHub Desktop.
Drupal & JavaScript integrations: testing Drupal.behaviors
(function ($) {
  'use strict';
  Drupal.behaviors.usingcontext_one = {
    attach: function() {
    // This will execute always after a load (whole DOM) or reload (partial AJAX). 
      $("#unsplash").append('<p>Hello world by Behavior One</p>');    }
  };

  Drupal.behaviors.usingcontext_two = {
    attach: function() {
    // Same behavior than the former.
      $(document).find("#unsplash").append('<p>Hello world by Behavior Two</p>');
    }
  };

  Drupal.behaviors.usingcontext_three = {
    attach: function(context) {
    // More refined than formers using the variable 'context'. 
      $(context).find('#unsplash').append('<p>Hello world by Behavior Three</p>');
    }
  };
  
  Drupal.behaviors.usingcontext_four = {
    attach: function(context) {
    // Using context and looking for the selector through jQuery.
    // Thanks to Ramon Vilar @rvilar for the feedback. 
       $('#unsplash', context).append('<p>Hello world by Behavior Four</p>');
    }
  };
 


  Drupal.behaviors.usingcontext_five = {
    attach: function() {
    // This will work only once due to the use of jQuery.once() method but load whole DOM.
      $('#unsplash').once('cacafuti').append('<p>Hello world by Behavior Five</p>');
    }
  };

  Drupal.behaviors.usingcontext_six = {
    attach: function(context, settings) {
    // Using jQuery.once() too but calling before the append. 
      $(context).once('cacafuti2').find('#unsplash').append('<p>Hello world by Behavior Six</p>');
    }
  };

}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment