I want to create a toggle effect on the 'active' class using JavaScript, with all JS code residing in my main.js file. I prefer not to include an onClick=toggle() attribute in my #readmore button. The onClick method functions correctly and toggles the 'active' class as desired. However, there is an issue when I use the code below – it automatically adds the 'active' class to .container and does not remove it when I click on #readmore. Additionally, I am looking for a solution that does not involve jQuery.
Here is the CODE:
var myBtn = document.querySelector("#readmore");
myBtn.addEventListener("click", toggle());
function toggle() {
document.querySelector(".container").classList.toggle('active');
};
<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>