Home > Net >  How to close a sidecart if i click outside of it
How to close a sidecart if i click outside of it

Time:03-28

i am trying to figure out how i can make my sidecart to close when i click outside of it, here is my scirpt:

const toggler = document.getElementById('menu-toggle');

const cartWrapper = document.getElementById('wrapper'); var crossButton = document.getElementById('closeCart');

// Displaying Menu Cart document.addEventListener('DOMContentLoaded', () => {

toggler.addEventListener('click', toggleCart);
crossButton.addEventListener('click',closeCart);

function toggleCart(){

    cartWrapper.classList.toggle('menuDisplayed');
    cartWrapper.classList.toggle('menuDisplayedBgColor');

}

function closeCart(){

    cartWrapper.classList.toggle('menuDisplayed');
    cartWrapper.classList.toggle('menuDisplayedBgColor');
}




});

toggler is button that opens sidecart cartWrapper is the sidecart and crossButton the cross button that close the sidecart

Here is my sidecart:

enter image description here

If you want more information about my code i would appreciate it if you tell me, Thank you!

CodePudding user response:

Well you can just click EventListener to the elements opening outside the sideCart.... ! Btw one question here where you want to get clicked.... you just need to add click event listener outside of this cart thing.. and you are pretty much good to go... !

CodePudding user response:

Hope this Code will help you.

window.document.addEventListener('click', (e) => {
    if (document.getElementById('menu-toggle') === e.path[1]) {
        cartWrapper.classList.toggle('menuDisplayed');
        cartWrapper.classList.toggle('menuDisplayedBgColor');
    }
    else {
        cartWrapper.classList.toggle('menuDisplayed');
        cartWrapper.classList.toggle('menuDisplayedBgColor');
    }
});

CodePudding user response:

  if (cartWrapper.hasClass("menuDisplayed")) {
    $("body").on("click", function() {
           closeCart();
       });
       cartWrapper.on("click", function(event) {
            event.stopPropagation();
       });
 });
  • Related