How come my JavaScript function is triggering without me clicking anything?

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>

Answer №1

toggle gets called when the event listener is added:

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

The correct way is to pass the function as a reference:

myButton.addEventListener("click", toggle);

Answer №2

When you write the code snippet

myBtn.addEventListener("click",toggle());
, you are actually invoking the function immediately instead of attaching it to the event listener. To correct this, you need to pass a reference to the function in the addEventListener method like so:

Update your code to look something similar to this -

myBtn.addEventListener("click", toggle);

Answer №3

To properly use the second parameter which expects a function reference, you must provide one instead of immediately calling the function and passing its result in your code.

The correct way to do this is as follows:

myBtn.addEventListener("click", toggle);

For more information, please refer to the documentation: MDN addEventListener. Now, the listener will be able to detect the click event and execute the function accordingly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Reducing the size of JavaScript code using C# in ASP.NET

I'm currently working on developing a templated user control that accepts JavaScript code as a template input from the user. My goal is to minify this code on the fly during the OnInit phase and then display the minified version of the JS. This requ ...

Tips for visually comparing two large JavaScript objects using two separate console.log statements

When working with C++, I usually print the address of objects and compare them to see if they are the same. How can I achieve something similar in JavaScript? Since I don't have direct references to the objects at the same time, I often resort to usin ...

Trouble arises when jquery's "position().top" clashes with the CSS3 property "transform: scale()"

Currently, I am working on adding a font resizer feature to my editing tool. To implement this, I made some changes to the text elements where their origin is now set to the bottom left corner. The normal version of the tool works perfectly fine, but when ...

What is the most effective way to retrieve all child Elements within a parent container?

Is there a way to retrieve all descendant elements within the parent container and store them in an array? <div class="parent"> <div class="child1"> <span class="child2"> <div class="child3"> ...

Exploring plyr and vue.js: utilizing a computed property to fetch video duration

I am currently attempting to load content dynamically based on the duration of a video being displayed. However, I am encountering issues when trying to access the duration property. Could this problem be related to the timing of plyr's appearance wit ...

Accessing a JavaScript object outside of its containing JavaScript file within a Dojo

I am working on a Dojo application that includes a Dgrid. My objective is to send the javascript containing the dgrid data to the server. However, I am encountering difficulties in accessing the javascript object beyond the file where it is defined. The a ...

Error: Unable to use 'UserContext' until it has been initialized - React

I am attempting to establish a UserContext that can be accessed by all class components within the React application. However, I am encountering the following error message. ReferenceError: Cannot access 'UserContext' before initialization App.j ...

Is there a way to have only the <a> tag be clickable in an unordered list, without making the entire list item clickable?

I just need the text to be made clickable instead of the entire list item block. <a class="menu_head">Hello</a> <ul class="menu_body"> <li><a href="#">Sub-menu 1</a></li> <li><a href="#">Sub-menu 2 ...

Troubleshooting: Issue encountered while declaring a GraphQLList containing a user-defined type within a GraphQLObjectType

Currently, I am diving into the world of GraphQL by working on a project that simulates a Book-Shop environment where users can have multiple books associated with them as authors. One issue I am facing is defining a list of type "BookType" within the Use ...

`Why am I having difficulty transmitting HTML content with Node.js through Mailgun?`

I've been facing issues with sending HTML in my emails. To troubleshoot and prevent errors, I've opted to utilize Mailgun's email templates. Although I can successfully send out the emails, the problem arises when I receive them - the HTML ...

Creating PHP functions that return a JSON string when invoked - a simple guide

I have created a script that contains various functionalities, including fetching data from a database and encoding it into JSON. However, I want to be able to call different functions to execute these scripts separately. When I attempted to define and c ...

Locate a DOM element by its attribute identifier

Is there a way to use jQuery to find a DOM element based on the name of its attribute, rather than the attribute value? For instance: <div id="div1"> <div id="div2" myattr="myvalue"> </div> </div> I want to locate all element ...

Having trouble with the installation of nodemon globally on macOS Mojave?

When using the Visual Studio Code terminal, I ran the following command: npm install -g nodemon The output in the terminal showed: npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules npm ERR! code EACCES npm ERR! syscall access n ...

Utilize the sortable script for dynamically loaded items via AJAX

For the drag and drop feature on my website, I am using jQuery sortable. I have a button that displays results with items on the screen. These items can be dragged and dropped into various sections. The issue I'm facing is that if I include the sort ...

Struggling with this <form> and need help adding space or a line break after form entry

I want to preface this by admitting that HTML is not my strong suit. I have a basic understanding, and I'm manually creating my website for simple tasks like hosting a magazine and videos. I apologize if my question seems naive or straightforward, but ...

Tips for reducing the size of your JavaScript buffer

Is it the correct way to convert a buffer to a string, trim it, and then convert back to a buffer in Node.js v6.12.x? var buf = Buffer.alloc(xxxxxx); ..... // buffer receives its value ..... let buffParsed = String.fromCharCode.apply(null, buf); buffPa ...

What is the best way to structure an XML document?

After successfully cURLing the JSS Casper API in PHP and receiving a response in XML, I noticed that in the browser, the XML is displayed without any whitespace, all on one line. Here's an example of the XML data: <accounts> <users> ...

The text inside the text box remains visible even after the Ajax call

My website features a chat room where users can type messages into a textbox. Upon hitting enter or clicking the send button, jQuery is supposed to take the data from the textbox, disable it, send the data to a file called send.php for processing and stora ...

Having issues with angular-file-upload failing to include the file in the request

I am currently using angular-file-upload in order to upload an image to a server that is utilizing Node and Express 4.0. However, I am encountering difficulties in accessing the file data on the server. Below is the relevant code snippet: <input type= ...

Tips for implementing multiple associations, conditions, and includes in node.js sequelize when using findAll

Currently, I am utilizing sequelize in node.js to access a mysql DB. My goal is to perform a join operation on 3 tables with the following relationship: Person n : n Work (related through PersonWork which has foreign keys for Person and Work) Work n : n ...