Home > OS >  A button do thing on clicking & undo it on another click
A button do thing on clicking & undo it on another click

Time:07-20

Hello,

I want to achieve the following:

When Button is clicked CSS Style changes to display: block on second click must be changed to display: none. And it must be looped

How to achieve that?

I managed to create this code which adds css style when clicked(but I can't make second click event):

const button = document.querySelector('button'); button.addEventListener('click', () => { const element = document.querySelector('div.wpcs_price_info ul'); element.setAttribute('style', 'display:block !important'); });

CodePudding user response:

Pretty easy, just add a if condition.

const button = document.querySelector("button");
let shown = false;
button.addEventListener("click", () => {
    const element = document.querySelector("div.wpcs_price_info ul");
    if (shown) {
        element.setAttribute("style", "display:none !important");
        shown = false;
    } else {
        element.setAttribute("style", "display:block !important");
        shown = true;
    }
});
  • Related