Javascript Button Hover works only once

I’m trying to implement some button which displays list items on hover.

It works good however it stops working after the first hover then I need to keep refreshing the page for it to work again.

Please see the code below;

var btn = document.getElementsByClassName("collapsible"); 
            
                    btn[0].addEventListener("click", function () { 
                        this.classList.toggle("active"); 
                        var content = this.nextElementSibling; 
                        if (content.style.display === "block") { 
                            content.style.display = "none"; 
                        } else { 
                            content.style.display = "block"; 
                        } 
                    }); 

Is there anyway I can make it work again and again without having to refresh the page?

1 thought on “Javascript Button Hover works only once”

  1. This is very simple to do with CSS. + is the sibling combinator.

    const btn = document.getElementsByClassName("collapsible"); 
                
    btn[0].addEventListener("click", function () { 
        this.classList.toggle("active"); 
    });
    .collapsible + * {
      display: none;
    }
    
    .collapsible.active + * {
      display: block;
    }
    <button class="collapsible">Click Me!</button>
    <p>
     Hello There!
    <p>
    Reply

Leave a Comment