The JavaScript function I coded is capable of executing on its own without needing

The code snippet above defines a function called tablePush that is supposed to push an id to a table when an item is clicked. However, there seems to be an issue as the function executes without a click event.

Below is the provided code block:

function tablePush() {
    console.log('OK');
    if (pickPicture) {
        console.log('TRUE');
    } else {
        console.log('on rentre dans le else');
        console.log(this);
        var idPic = this.getAttribute('id');
        console.log(idPic);
        table.push(idPic);
        pickPicture = true;
    }
}

var picture = document.getElementsByClassName('picture'),
    table = [],
    pickPicture = false;

for (var i = 0; i < picture.length; i++){
    picture[i].addEventListener('click', tablePush());
}

Answer №1

In this scenario:

When you write picture[i].addEventListener('click', tablePush());
                                                    ^^

Instead of adding the function tablePush, it actually adds the result of calling tablePush(). The parentheses () indicate that the function should be executed immediately. To resolve the issue, modify your code like this:

picture[i].addEventListener('click', tablePush);
                                              ^ remove parentheses

Answer №2

When you call a function and add an event listener at the same time.

You should change

picture[i].addEventListener('click', tablePush());

to

picture[i].addEventListener('click', tablePush);

Answer №3

The call is being made.
The correct approach is to declare the function tablePush (not to execute it):

picture[i].addEventListener('click', tablePush);

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

Ways to alter the color of an icon when hovering over it

Is there a way to change the color of a material icon inside an IconButton material component when hovering over the IconButton? I've tried adding a class directly to the icon, but it only works when hovering over the icon itself and not the IconButto ...

Implementing mouse event listeners on dynamically created elements in Vue.js

I've been curious if anyone has attempted something similar to the following code snippet (created within a Vue.js method): for (let i = 0; i < this.items.length; i++) { let bar = document.createElement('div'); bar.className = this ...

What is the best way to know which API will return the result the fastest?

If we were to make 2 API calls, each taking around 6ms to return JSON data, what would be the sequence in which they provide the resulting data? The official JavaScript documentation mentions using Promise.all to manage multiple API calls. ...

Bootstrap - Keeping track of the collapse state of <div> elements after page refresh

Looking for some guidance as a javascript/jquery beginner - I am utilizing Bootstrap along with data-toggle and collapse classes to display or hide divs. I have been searching online trying to find a solution that will maintain the state of all divs, wheth ...

Tips for choosing an image using jQuery from an external HTML page

I'm attempting to embed an HTML page within a div and then individually select all the img tags within that page to display an overlay div on top of the images. Currently, I can insert the HTML into a div named "asd" and it seems like the jQuery is f ...

Determine the initial left position of a div element in CSS prior to applying

Scenario : const display = document.querySelector('.display'); const container = document.querySelector('.outer-div'); document.addEventListener("click", (event) => { if (!event.target.closest("button")) return; if(event ...

The HTML button triggers a function to execute on a different webpage when clicked

I'm facing a straightforward issue that I can't seem to figure out due to my limited experience with Angular and web development. The problem revolves around two components, namely home and dashboard. In the home.component.html file, there's ...

enhanced labeling for checkboxes in Vuetify

Below is a snippet of my straightforward code: <v-checkbox v-model="rodo" label="I consent to Terms and Conditions (click for more info)" :rules="termsRules" required ></v-checkbox> I am looking to keep the label simple with an option ...

How can I connect a click event on one div to trigger another using jquery?

Could someone assist me with the proper terminology? I am interested in clicking one div, which would then automatically trigger the click on another div. For example, if I click on div 1, I want div 2 to be clicked by JavaScript without user interaction ...

The YUI framework is skilled at creating new lines while erasing the old ones

I am looking to create a line when the mouse is clicked, and remove the previously drawn line. View the code on jsfiddle.net at this link. While my current code successfully draws a line when the mouse is clicked, it does not remove the previous line. I n ...

Retrieving API Data in React Using the MERN Stack

Can anyone help me understand why I'm logging an empty array [] in my console even though I'm getting results from my API? This is my Node.js code: app.get("/todos", async (req, res) => { const todos = await todo.find() res.json(todos ...

What is the best way to trigger a refresh callback on Angular datatable pagination after updating the data

I've successfully set up my angular datatable configuration. Here's what it looks like: vm.dtOptions = DTOptionsBuilder.newOptions(). withPaginationType('full_numbers'). //withOption('ajax', { ...

Merge multiple list groups into one with a single active selection using Bootstrap List group functionality

Currently, I am experimenting with merging Bootstrap's accordion and list group with JS behavior. My goal is to create a set of list groups where only one option can be active at a time within each accordion. <link rel="stylesheet" href="https:/ ...

Is there a way to enable text selection on a jQuery draggable div?

I utilized jQuery to make a specific div draggable, but I've encountered an issue. Inside this draggable box, there is some important text that I need to be able to copy and paste. However, whenever I click on the box, it triggers the dragging action ...

What is the best way to group Angular $http.get() requests for efficiency?

My challenge involves a controller that must retrieve two distinct REST resources to populate two dropdowns. I want to ensure that neither dropdown is populated until both $http.get() calls have completed, so that the options are displayed simultaneously r ...

Struggling with validating forms with JavaScript

I'm having trouble with the following JavaScript code: <script type="text/javascript"> function checkDetails(search) { var search = documment.getElementById('query'); if(search.value ==''||search.val ...

Tips for eliminating the domain name from the src URL attribute using Jquery

Is there a way to extract the img src attribute and retrieve only the image path without the domain name included? var imgurl = "http://nitseditor.dev/img/home/bg.jpg"; For instance, I would like to display img/home/bg.jpg instead of the full URL. Any id ...

Issue with passing multiple promises to $q.all function

Currently, I am attempting to iterate through an object and fetch data for each iteration from two separate service API functions. These functions return promises due to using the $http object, which means I must wait for the responses before populating my ...

Using jQuery to locate a JavaScript variable is a common practice in web development

I recently created a JSFiddle with buttons. As part of my journey to learn jQuery, I have been converting old JavaScript fiddles into jQuery implementations. However, I seem to be facing a challenge when it comes to converting the way JavaScript fetches an ...

Utilize a foreach loop to store information as arrays in a MySQL database

My form is set up to submit multiple values using PHP. Here is the code snippet: echo "<form action='?ud=".$ud."' method='post'>Name: <input type='text' name='fname' />"; $resultw = mysql_query("SELE ...