Incorporate an onclick event to the elements within the array

I'm currently working on iterating over an array and adding an onclick event to each element. My goal is to be able to click on each div and have them log their values in the console. However, I am facing a challenge in applying the onclick event to each individual div. As a beginner in JavaScript, I am unsure why creating a function inside a loop would cause JSBin to raise an issue. Despite trying various approaches, I haven't been able to make progress...

JSBin

function numberTrack() {

  var gridItems = document.getElementsByClassName("grid");

  for (var i = 0; i < gridItems[0].length; i ++) {
    gridItems.onclick = function(){
      alert("hello");
    };
  }
}

numberTrack();

Answer №1

let divs = document.getElementsByClassName("divs");    <--- array of divs

for (let j = 0; j < divs.length; j++) {

    divs[j].onclick = function() {

        console.log(this.value);

    }

}

Answer №2

JSBin is giving you a heads up because it is suggesting to declare the function outside of the for loop and then assign it inside the loop for better efficiency. What you are currently doing is creating a new anonymous function for each item in the array, which requires extra memory to store all those identical functions.

A better approach would be like this:

function greetUser() {
  alert("Hello!");
}

for (var i = 0; i < gridItems.length; i++) {
    gridItems[i].onclick = greetUser;
}

Answer №3

To iterate through all the items in the gridItems collection, simply loop through them and retrieve each item using the iterator i value.

function handleClick()
{
  alert("hello");
}
function numberTrack() {

  var gridItems = document.getElementsByClassName("grid");

  for (var i = 0; i < gridItems.length; i ++) {
      gridItems[i].onclick = handleClick;
  }
}

numberTrack();

If jQuery is an option for you, you can bind events to items like shown below:

$(function(){
  $(document).on("click",".grid",function(e){
      var item =$(this);
      alert(item.html())
  })
})

Here is a working example on jsBin

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

Calculating the total of all values in a table

For my ngFor loop, the invoice total is calculated based on price and hours, but I also want to calculate the totals of all invoices in the end. <tr *ngFor="let invoice of invoiceItem.rows"> <td>{{ invoice.rowName }}</td> <td& ...

Launching a modal using a method in Vue.js that includes constantly changing content

I am currently developing a feature in my VueJs component that involves opening a modal when a certain condition becomes true, and then retrieving data from a controller to display in the modal. After searching online, I have not been able to find clear i ...

How can I overlay a background image on top of another div?

This inquiry might not be the most trendy, but I am seeking guidance on the best approach to tackle this task, utilizing HTML, CSS, and Bootstrap. For reference, something similar to the image at this link. ...

Restricting the Vue for-loop results to display only the current item in use

Currently, I am utilizing a for-loop to retrieve all of my posts, followed by employing a partial to obtain a list of all the usersThatUpvoted on that post. <div v-for="p in posts" style="padding: 16px"> <div> &l ...

Creating visually appealing websites is made easy with Bootstrap 5's innovative image and

I am working on a Bootstrap 5 website template and I want to add text with a white background in the center of an image. Instead of seeing just a white color over the image, I would like to have a white rectangle with a title and text centered on the imag ...

What steps can be taken to modify the style of a single button belonging to a broader group of elements?

Is there a way to hide the save button within a Vue Modal without affecting other buttons with the same class? .btn.btn-primary { display: none; } Simply targeting .btn-primary in the CSS affects all elements with that class, and adding .modal woul ...

Store data in Laravel's storage directory

I encountered an issue while trying to save files to the storage folder in Laravel after deploying the project on a web server (byethost7.com). The files were only being stored in the public folder. I ran the following command in the command prompt: >p ...

Validation of time picker consistently returns false

While using the daterangepicker library for my form validation with JavaScript, I encountered an issue with the time field. It returns false and displays an error message saying: "Please enter a valid time, between 00:00 and 23:59," preventing me from addi ...

Leveraging a Static HTML landing page template within an Angular 6 application

I currently have an Angular 6 app hosted on example.com, with the dist folder being served on port 5000. Additionally, I have a separate landing page folder with its HTML, CSS, and JS files being served on port 6000 at example.com/welcome. Is there a way ...

Is it possible to achieve a smooth transition to the right using CSS

I'm attempting to create a sliding box effect from left to right using only transitions, similar to this: #box { width: 150px; height: 150px; background: red; position:absolute; transition: all 2s ease-out; right:auto; } .active{ bac ...

Implementing a restricted Mongoose promise loop iteration count

Currently, I am developing an online store using Node, Express, and Mongoose. In the postCheckout Controller, which is responsible for handling user purchases, I am facing an issue. When a user buys a product with a quantity of 5, the code should check i ...

Add a dynamic widget to a specific element in the document object model in real time

Is there a way to dynamically create a jQuery UI widget using a string? You can easily do this by following the example below: $(function() { $("selector").widget() }) However, what I am trying to accomplish is slightly different. Here is an examp ...

If one sibling requires flexing, apply flex to all siblings

Illustrative Issue: large: https://i.sstatic.net/oq0jA.png small: https://i.sstatic.net/WXqmV.png When space is limited, one row will start to flex while others remain static if they have enough space. Is there a way to make all rows flex when at least ...

Saving data in HTML using PHP and then downloading it

Currently, I am tackling a project involving a website that is connected using PHP. The main function of the PHP script is to modify an HTML file stored on the server and then allow the user to download it. I attempted to use PHP DOM for this task but unf ...

How can I detect when an image is loaded in a specific container division using jQuery?

I have a container with multiple images inside, and I would like to capture an event each time an image finishes loading. For example: <div id="container"> <img src="..." /> <img src="..." /> <img src="..." /> ...

Can you customize the "rem" values for individual Web Components when using Angular 2's ViewEncapsulation.Native feature?

I'm interested in creating a component with ViewEncapsulation.Native that utilizes Bootstrap 4 while others are using Bootstrap 3. Below is the component code with Bootstrap 4: import { Component, ViewEncapsulation } from '@angular/core'; i ...

The addEventListener function seems to be malfunctioning in the React JS component

Initially, the program runs correctly. However, after pressing the sum or minus button, the function fails to execute. componentDidMount() { if(CONST.INTRO) { this.showIntro(); // display popup with next and previous buttons let plus = docume ...

python extract values from a JSON object

I've been searching everywhere, but I haven't been able to find a solution. It seems like my question is not clear enough, so I'm hoping to receive some guidance. Currently, I am working with turbogears2.2. In my client view, I am sending a ...

Adding the !important rule in React inline CSS effortlessly

Is there a way to include !important in my inline CSS property without disrupting the entire style? import React from "react"; export default class Todo extends React.Component { render() { const {text} = this.props; const cardStyl ...

Vue: the parent template does not permit the use of v-for directives

Upon creating a simple post list component, I encountered an error when trying to utilize the v-for directive: "eslint-eslint: the template root disallows v-for directives" How can I go about iterating through and displaying each post? To pass data from ...