multiple event listeners combined into a single function

I'm looking to streamline my button handling in JavaScript by creating just one function that can handle all the buttons on my page. Each button will trigger a different action, so I need a way to differentiate between them. I thought of using one event listener for all the buttons, but how do I identify which button was clicked based on its ID?

<div class="col-11" id="btns">
         <button class="btn btn-dark" id="btn1">Button 1</button>
         <button class="btn btn-dark" id="btn2">Button 2</button>
         <button class="btn btn-red" id="btn3">Button 3</button>
         <button class="btn btn-blue" id="btn4">Button 4</button>
</div>

let btnContainer = document.getElementById('btns');
btnContainer.addEventListener("click", handleButtonClick);

function handleButtonClick(e){
    if(e.target.id === 'btn1'){
        console.log("Hello");
    } else if(e.target.id === 'btn2'){
       // do something...
    }
}

Answer №1

Your approach is on the right track, but there's a small error in your code that needs to be addressed:

e.target.id===document.getElementById('btn1')

What you are doing here is comparing the ID of the clicked element to the element with the ID 'btn1'.

The problem lies in comparing a string to an element, which will always result in false.

A better way to compare would be:

e.target===document.getElementById('btn1')

This comparison involves an element being compared to another element.

Alternatively, you can use:

e.target.id==='btn1'

Here, you are comparing a string to a string.

Tip: To simplify your code, consider using a switch/case block instead of multiple if statements. Here's how you could rewrite your click handler:

function doStuff(e) {
    switch(e.target.id){
        case 'btn1':
            // Code for btn1...
            break;
        case 'btn2':
            // Code for btn2...
            break;
    }
}

For more information on switch/case, check out: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch

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

Having trouble with the scrollbar appearance after updating Chrome?

I've encountered an issue with my code after the latest Chrome update. Is there a way to implement cross-browser styling for scrollbars? // Looking for Scrollbar Styling Solution const scrollbarStyle = { scrollbarColor: `${themeLayers.scrollBar[0 ...

Is incorporating RequireJS into an AngularJS project a valuable decision?

Is it true that AngularJS has its own module loading mechanism built-in and using RequireJS is unnecessary or even inefficient? I am working on an Angular project where the index.html file is becoming quite large. Would incorporating RequireJS help reduc ...

What are the steps to utilize vue.js for dynamically adjusting my sidebar based on a URL input?

Greetings to the amazing community of Vue.js enthusiasts, I am a novice looking to develop a single-page web application using vue.js. This application will consist of a fixed header and dynamic body content that changes based on user interactions. Here&a ...

Exploring the Past: How the History API, Ajax Pages, and

I have a layout for my website that looks like this IMAGE I am experimenting with creating page transitions using ajax and the history API. CODE: history.pushState(null, null, "/members/" + dataLink + ".php" ); // update URL console. ...

Finding and removing the last portion of the innerHTML can be achieved by employing specific techniques

Looking to manipulate a <div> element that includes both HTML elements and text? You're in luck. I need to locate and remove either the last, nth-from-last, or nth plain text section within it. For example: <div id="foo"> < ...

Access data from previous request and transmit it to another request in a Node.js environment

I am facing a situation where I need to extract the parsed json response from a variable in a POST request, store it in a new variable, and then pass that variable in the headers for a subsequent GET request. However, my current approach is not yielding th ...

Initializing start scripts in the package.json file

When launching my react app locally, I need to execute three commands: cd react-web npm run postinstall export REACT_APP_CUSTOMER_ENVIRONMENT=xxx npm start After running these commands, the application server starts on localhost:3000. For the start script ...

I can't see the presence of spin.js on my website

I am completely new to Javascript and I'm trying to implement a loading spinner on my website. Whenever users tap the screen, it takes some time to navigate to the desired URL, so we need a spinner to prevent them from tapping repeatedly. I decided t ...

Bootstrap modal fails to appear on screen

Using PHP, I generate a link from the controller. The link is stored in $retailer["url"] as 0125myimage.jpg <a onClick="crop('.$retailer["url"].')" data-target="#styledModal3" href="#" class="fa fa-edit lupa"></a> Here is my JavaSc ...

What is the most effective method for updating a className in Next.js using CSS Modules when a button is activated?

Looking to create a responsive navigation bar that transforms based on screen size? When the width reaches 600px, I'd like to hide the links and instead show a clickable nav button that reveals those options. Upon inspecting my list elements in the c ...

Filling a martial arts training center's drop-down menu with choices using an Ajax response message

Within my application, there are two drop down menus. The first drop down menu allows users to select the type of institution, and I have added an onchange event that triggers a JavaScript function to make an AJAX call in order to populate the second drop ...

Transforming JSON in Node.js based on JSON key

I am having trouble transforming the JSON result below into a filtered format. const result = [ { id: 'e7a51e2a-384c-41ea-960c-bcd00c797629', type: 'Interstitial (320x480)', country: 'ABC', enabled: true, ...

Steps for implementing Onclick event within the <Script> tag to display a div:

I am currently working on a code that allows me to show and hide a <div> element after clicking on an advertisement from any website. This advertisement is generated by a script. How can I implement the onclick event within the <script> tag? T ...

Calculating the total value in a Laravel database

Is there a way for me to calculate the number of apartments in a project based on the floor they are located on? This is db $table->id(); $table->unsignedBigInteger('project_building_id')->nullable(); $table->unsignedBigInteger(&apos ...

Sending a multitude of variables using strings, evaluating them through various functions, and incorporating a variety of methods

To put it simply, my goal is to utilize an object literal that allows me to pass an unknown quantity of variables in any order to a function. While this may seem straightforward in principle, within my code, this object literal is passed to a second functi ...

The flag will never turn true; it's stuck in the false position

Currently, I am in the process of developing a custom hook to store data on a server. To mimic the server call, I have implemented a simple setTimeout function that changes the value of the data creation flag to true after 2 seconds. I have a specific fun ...

Retrieve information from a JSON file within a Vue.js application rather than entering data manually

I am venturing into the world of Vue.js for the first time. I have created an app that currently relies on manually added data within the script. Now, I am looking to enhance it by fetching data from a JSON file, but I'm unsure about how to proceed wi ...

Invoking WinJS.Binding.List.createFiltered with an asynchronous call to the predicate function

Is there a way to wait for the async operation in this code snippet and use its result as the predicate instead of always returning false? return someList.createFiltered(function(item) { var filter = false; var ...

Node.js readline: SyntaxError: Unexpected token =>

Currently, I am diving into node.js and have found myself in need of utilizing the readline module for a new project. Below is the code snippet that I extracted directly from the official readline module example. const readline = require('readline&ap ...

Tips for refreshing views with Angular JS

I am looking to refresh all the views displayed on my page. The layout consists of a Header, Footer, and Body view. Within the Header view, there is a dropdown menu where users can choose their preferred language. Upon selecting a language, I want all the ...