Tips for creating a single event listener that applies to all buttons

Is there a way to efficiently add an event listener to multiple buttons and retrieve the value of each one based on the one that was clicked? For example:

<button id='but1'>
Button1
</button>
<button id='but2'>
Button2
</button>
<button id='but3'>
Button3
</button>
<button id='but4'>
Button4
</button>

Without having to individually reference each button in the JavaScript code like this:

Const but1 = document.getElementById('but1'); 
but1.addEventListener('click');

Answer №1

Instead of adding listeners to each button individually, you can utilize the concept of Bubbling and capturing in JavaScript. By wrapping all your buttons within a div, you can catch all the events there. Just ensure that you verify if the click occurred on a button rather than the div itself.

const wrapper = document.getElementById('wrapper');

wrapper.addEventListener('click', (event) => {
  const isButton = event.target.nodeName === 'BUTTON';
  if (!isButton) {
    return;
  }

  console.dir(event.target.id);
})
div {
  padding: 20px;
  border: 1px solid black;
}
<div id='wrapper'>
  <button id='but1'>
  Button1
  </button>
  <button id='but2'>
  Button2
  </button>
  <button id='but3'>
  Button3
  </button>
  <button id='but4'>
  Button4
  </button>
</div>

Answer №2

If you have buttons without a common class, you can utilize the following code:

button[id^=but]

This code allows you to target any button with an id that starts with but, essentially matching but* where * acts as a wildcard.

const btns = document.querySelectorAll('button[id^=but]')

btns.forEach(btn => {

   btn.addEventListener('click', event => {
        console.log( event.target.id );
   });

});
<button id='but1'>Button1</button>
<button id='but2'>Button2</button>
<button id='but3'>Button3</button>
<button id='but4'>Button4</button>

Answer №3

Instead of using ids, opt for using classes to target multiple buttons at once.

<button class="btn">
Button A
</button>
<button class="btn">
Button B
</button>
<button class="btn">
Button C
</button>
<button class="btn">
Button D
</button>

Then, in your JavaScript:

const btns = document.querySelectorAll('.btn')
btns.forEach(function(btn){
  btn.addEventListener('click', handleClick)
})

You can iterate through the NodeList stored in the 'btns' constant, which contains all the selected buttons. Learn more about document.querySelectorAll here

Answer №4

Similar to Lucas's response, this solution utilizes classes for button selection instead of IDs and employs a simple for loop.

<button class="btn">
    Button A
</button>
<button class="btn">
    Button B
</button>
<button class="btn">
    Button C
</button>
<button class="btn">
    Button D
</button>

The JavaScript code:

var buttons = document.querySelectorAll(".btn").length;

for (var i = 0; i < buttons ; i++) {
    document.querySelectorAll(".btn")[i].addEventListener("click", function() {
        alert("Button Clicked");
    });
}

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

Animate only the items that have been loaded last (using the ajax load more feature)

One of the pages I'm working on displays a list of items, and when you click a button, more items are loaded. The div surrounding these items has a class that triggers an animation. The Issue: Every time the button is clicked, the entire script is r ...

When using my webrtc technology, I configure my sdp to establish a recvonly direction

While attempting to make a video call using WebRTC, I encountered bugs during testing. My goal is to integrate this project into a webview for my Android app. I conducted testing using phone-pc and phone-phone scenarios. Scenario A: When the PC initialize ...

Iterate over the array elements in React by using Hooks on click

I am facing an issue with loading objects separately from a JSON file when a button is clicked. The problem occurs when the index goes out of bounds, resulting in a TypeError "Cannot read property 'content' of undefined" message. I have tried u ...

User Interface Components in Backbone Views

I'm considering if there is a more efficient approach to this situation. I've got some HTML that requires event handling. Query 1: Since there are no data, models, or collections associated with it, do I need a render method? Query 2: I believ ...

Anticipated a task or method invocation but encountered an expression instead no-unused-expressions (line 14/15)

I can't seem to figure out the issue with my code. Despite trying to fix it multiple times by adjusting lines 14/15, I keep encountering the same error. If anyone has any insights or suggestions on what might be causing this problem, I would greatly a ...

Running unit tests on the interceptor using axios results in an error

I'm currently working on writing Unit tests for my Nestapp. Specifically, I am focusing on the interceptor file and trying to create a test case that will throw an error when the condition error.message.indexOf('timeout') >= 0 is met, and ...

Despite the value being true, the if statement does not work when used with a Mongoose object in Node.js

Currently working on a bidding app, Below is the schema for the bidding model const bidSchema = new mongoose.Schema({ name: String, price : Number, description: String, location: String, specilization: String, image: String, ...

Guide to incorporating React component with Postgres database

I'm confused about a scenario where I have created a React project with the command npx create-my-app myProject, and within the public folder, there are multiple folders containing NodeJS for a Postgres database. My question is, if I need to access da ...

Transforming each element of an observable array by updating their properties with data retrieved from an ajax request using knockout

In my ViewModel "AppViewModel", I am fetching JSON data to create the model. One of the properties, "totalSessions", requires an ajax call to be fetched. While my code runs without errors, the view does not update as expected. var jsonapparray = []; ...

The function of JQuery .click() is successful when used on a local machine, however it is not functioning

I am facing a puzzling issue. The code in question functions perfectly on my local server, but once I uploaded it to my hostgator server, a specific function no longer executes. When I set a breakpoint in the Firefox debugger, I noticed that the function i ...

Nodemailer is failing to send emails on Heroku

Recently, I encountered an issue that has been puzzling me. I use cloud9 for work and nodemailer works perfectly fine, sending all emails from a form I created. However, when I deployed a small server to Heroku with just a change in an environmental vari ...

Changing the input to uppercase within Vue.js

I am looking to capitalize the input data from the user's full name model and would prefer if it is in Latin letters only. Utilizing Vue.js for Uppercase Conversion <p-input :value="value" @input="$emit('input', $event)&qu ...

How to retrieve a specific item from an array in JavaScript

I am retrieving this list from the server using PHP: ["Ak-Bulak","Balykchy","Batken"] How can I access it and insert it into select options using JavaScript? Here is what I have tried so far: for (var i in data) { $('#cities').append(' ...

Trouble with HTML2PDF.js - download not being initiated

Currently, I am utilizing html2pdf.js in my project by following this tutorial: https://github.com/eKoopmans/html2pdf.js However, I've encountered an issue where despite implementing everything as instructed, the download prompt for the specified div ...

Using Array Data Format to Customize Color in Highcharts Funnel Chart

I have included the funnel visualization code that I've been working on. $(function() { var dataEx = [ ['1 Visit', 352000], ['2 Visits', 88000], ['3+ Visits', 42000] ], len = dataEx.length, ...

Using GET Parameters in POST Requests with Laravel

I am currently utilizing jQuery AJAX to transmit map coordinates to a controller via POST method. I am now contemplating. If the current page is site.com/project/2 How can I effectively pass the 2 along with the POST data? Possible Solutions I Have Co ...

What is the trick to displaying Bootstrap 5 dropdown arrows when the button label is lengthy?

Within a fixed-width element, I have a Bootstrap dropdown which causes the arrow to disappear when the button text is too long. Is there a way to trim the text while still displaying the arrow, similar to this image: https://i.sstatic.net/jHp5R.png .ou ...

"Is there a way to initiate a Date Picker with the current date using Javascript in an AngularJS application

I am having an issue with my date picker where the month starts from the current month and goes up to the next 12 months. However, I only want to display dates from the current date to the last date of the current month. I believe I need to set a limit so ...

Using Vue.js to eliminate duplicate values from a filtered array of objects

How can I eliminate duplicate data from a v-for loop in Vue.js? I have an array of clients and another array of categories. When filtering the categories based on clientIDs, I noticed that there are duplicates present. Please choose a client from the opti ...

Mongodb Retrieving results and their opposites

Can you retrieve results that match a specific query and those that do not in a single query? Assume I have the following data: { name: 'name1', age: 19 }, { name: 'name2', age: 20 }, { name: 'name3', ...