0

Maybe someone of you has already encountered this weird problem that I am having. I have javascript code that runs fine when you are an anonymous user and no longer works when authenticating. The library is loaded, but the code does not execute. Does this speak to anyone? My drupal version is 8.9.2 and the code in question :

(function ($, Drupal) {
Drupal.behaviors.toto = {
attach(context, settings) {
  $('.block--toto ul', context).once('toto-behavior').each(function() {

      let toto = $('.block--toto ul');
    let istotoActive = toto.find('li.is-active');

    toto
      .wrap('<div class="dropdown"></div>')
      .closest('.dropdown')
      .prepend('<button href="#toto" class="dropdown-toggle" data-toggle="dropdown">' + istotoActive.attr('hreflang') + '</button>');

    toto
      .addClass('dropdown-menu')
      .find('li').addClass('dropdown-item')
      .find('a').addClass('dropdown-link');
    $('.block--toto li').each(function () {
      $(this).on('click', function () {
        $(this).closest('.dropdown')
          .find('.dropdown-toggle').text($(this).text())
      })
    })

  });
}

}; })(jQuery, Drupal);

Thanks for help

6
  • did you clear cache after make new js changes? Might be js aggregation cause issue.
    – Cool
    Sep 16, 2020 at 13:01
  • @ARUN when i clear the caches the first time the code actually runs. But the problem reappears when I refresh the page
    – Touco
    Sep 16, 2020 at 13:08
  • Are you trying to manipulate the Admin Toolbar or Menu "active" states? Both of them are not rendered serverside, but updated asynchronously by JS. It can happen that a block container like .block--toto exists and the behavior triggers, but that an is-active class is added afterwards by JS, after your behavior has triggered.
    – Hudri
    Sep 16, 2020 at 13:21
  • When logged in you have a lot more Drupal.behaviors calls with different contexts and your code is not correctly handling it. The first line is correct, but then you assign toto globally instead of toto = $(this). Later it's the other way, the first line is missing context $('.block--toto li') while the rest seems to be OK.
    – 4uk4
    Sep 16, 2020 at 13:33
  • 1
    Thanks you gentlemen ! As you said @4k4 several Drupal.behaviors call with differents contexts when we log. It would seem in my case that the context was not the expected one. The issue was resolved by removing the context.
    – Touco
    Sep 16, 2020 at 15:48

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.