Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a cleaner way to call multiple toggles & elements during a click event listener with vanilla JavaScript?

Tags:

javascript

I have multiple toggles being called at the same time during a click /eventListener and it works but I'm wondering if there is a cleaner way to write the code where it doesn't look so repetitive.

Here is a snippet of the code I'm trying to refactor/clean up. Any help or point in the right direction is greatly appreciated. Thanks!

document.getElementById("menu-toggle").addEventListener("click", mobileMenuToggle);

function mobileMenuToggle() {
    var hideMenu = document.getElementById("mobile-menu-container");
        hideMenu.classList.toggle("hide-menu");

    var hideMenuIcon = document.getElementById("menu-toggle");
        hideMenuIcon.classList.toggle("hide-menu-icon");

    var closeMenuIcon = document.getElementById("close-menu-toggle");
        closeMenuIcon.classList.toggle("show-close-icon");

    var closeMenuIcon = document.getElementById("container-bg-toggle");
        closeMenuIcon.classList.toggle("show-icon-bg");
}
like image 251
ok88 Avatar asked Sep 24 '20 04:09

ok88


1 Answers

Few other options

  1. To make it more concise, you can get rid of references, which you are not reusing

    function mobileMenuToggle() {
      document.getElementById("mobile-menu-container").classList.toggle("hide-menu");
      document.getElementById("menu-toggle").classList.toggle("hide-menu-icon");
      document.getElementById("close-menu-toggle").classList.toggle("show-close-icon");
      document.getElementById("container-bg-toggle").classList.toggle("show-icon-bg");
    }
    
  2. In case if these elements are nested, You can just write a css rule and do one toggle

    #mobile-menu-container.hide-menu .menu-toggle {
      display:none;
    }
    
    #mobile-menu-container.hide-menu .close-menu-toggle {
      display:block;
    }
    

    And you can just toggle the parent container alone

     function mobileMenuToggle() {
       document.getElementById("mobile-menu-container").classList.toggle("hide-menu");
     }
    
  3. In case if you are using jquery, you can use the jquery toggle, which is bit short

    $('#mobile-menu-container').toggleClass('hide-menu');
    
like image 140
Yuvaraj G Avatar answered Nov 09 '22 01:11

Yuvaraj G