vendredi 31 juillet 2020

Why my JS function automatically fires without click?

Basically i would like to toggle class of 'active'. and I want all JS related codes in my main.js file. I mean I dont want my #readmore button to has onClick=toggle() inside its attribute. onClick method works fine, toggles my 'active' class. But the problem is without doing it. When I use code below, it automatically adds 'active' class to .container and doesnt removes when I click on #readmore. By the way, i dont want to use jQuery.
Thats is my CSS

<div class="container">
        <div class="content">
            <h2>
                Lorem ipsum dolor sit amet consectetur, adipisicing elit. Nesciunt, modi! Ipsum ab non voluptas facilis maxime architecto nulla consectetur recusandae.
            </h2>
            <img src="img/img4.jpg" alt="" width="600px">
            <a href="#" id="readmore">Read More</a>
        </div>

and my JS file

var myBtn = document.querySelector("#readmore");

myBtn.addEventListener("click",toggle());

function toggle(){
    document.querySelector(".container").classList.toggle('active');
};



Aucun commentaire:

Enregistrer un commentaire