0

On my site on the navigation panel I have a dropdown language switcher. (Dropdown Language Switcher module). I need to modify the js file and show the message to the user after he switched the language. What is the right way to modify js file?

(function ($, Drupal) {
'use strict';

Drupal.behaviors.dropdownLanguagesSelector = {
  attach: function(context, settings) {
   $('.dropdown-language-item .active-language', context).once('dropdown-language-selector')
    .click(function(e) {
      var $wrapper = $(this).closest('.dropbutton-wrapper');
      if ($wrapper.length > 0) {
        e.preventDefault();
        e.stopPropagation();
        $wrapper.toggleClass('open');
      }
    });
  }
};
})(jQuery, Drupal);    

Language switcher HTML looks like following:

<div class="dropbutton-widget">
 <ul class="dropdown-language-item dropbutton">
  <li class="fr dropbutton-action">
   <span class="language-link active-language" hreflang="fr">FR</span></li> 
  <li class="dropbutton-toggle"></li>
  <li class="en dropbutton-action secondary-action"></li>
  <li class="de dropbutton-action secondary-action"></li>
 </ul>
</div>

I am trying to attach following event:

$('.secondary-action').click(function(){
   alert(Message!);
})
  • Is the JS you showed at the start of the post working as you've shown it? – Jaypan Sep 21 '18 at 1:02
  • It is a contributed module. This js came with the package – badm Sep 21 '18 at 7:15
  • Ok, you wouldn't change that file then. You would use the code structure I gave below (which I'll update slightly according to your reply) – Jaypan Sep 21 '18 at 7:15
2

Here's a skeleton of how you can add functionality to elements using Drupal.behaviors.

(function ($, Drupal) {
  'use strict';

  // Create a new function for each element the file attaches
  // handlers to. In this case, $(.secondary-action')
  function secondaryEventListener(context) {
    // Find the elements, ensure that any internal code is executed
    // a single time using $.once(), then loop through the found elements
    // using $.each()
    $(context).find('.secondary-action').once('secondary-event-listener').each(function () {
      // $(this) refers to the current instance of $('secondary-action')
      $(this).click(function () {
        alert("clicked");
      });
    });
  }

  Drupal.behaviors.someArbitraryButUniqueKey = {
    attach: function(context, settings) {
      // Call your function containing the handlers
      secondaryEventListener(context);
    }
  };
}(jQuery, Drupal));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.