wasilikoslow
wasilikoslow

Reputation: 1963

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.

My 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>

Upvotes: 1

Views: 371

Answers (3)

0xAnon
0xAnon

Reputation: 897

Since the second parameter expects a function reference, you need to provide one. With your problematic code, you're immediately calling the function and passing its result

We need to do something like this:

myBtn.addEventListener("click", toggle);

You can check out the Docs: MDN addEventListener Now, listener will listen for your click event and will invoke the function for you.

Upvotes: 1

Yanjan. Kaf.
Yanjan. Kaf.

Reputation: 1725

In this case where you are writing myBtn.addEventListener("click",toggle()); you are calling the function at the same time but you should add a reference to the function, calling the function will done via the addEventListener.

so change your function to something like this - myBtn.addEventListener("click", toggle);

Upvotes: 2

Adam Azad
Adam Azad

Reputation: 11297

toggle is executed when attaching the event listener:

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

We want to pass the function reference:

myBtn.addEventListener("click", toggle);

Upvotes: 6

Related Questions