Triggering a click event on various instances of a similar element type using the onclick function

Hey there, I'm a newcomer to Javascript.

I've been practicing my Javascript skills and trying to replicate something similar to what was achieved in this example: Change Button color onClick

My goal is to have this functionality work for multiple "buttons" (inputs), so that when any button is clicked, only that specific button changes color.

I attempted to modify the example above to support multiple buttons, but unfortunately, clicking on any button simply changes the color of the first one.

If someone could provide an explanation or an example of how to make buttons behave independently, it would be incredibly helpful.

Answer №1

This solution is efficient:

  • It promotes a clear separation of concerns by avoiding the mixing of javascript code with html
  • There is no reliance on external libraries like jQuery

<html>
<head>
  <script>
    function initialize() {
      var buttons = document.querySelectorAll('input[type=button]');

      [].forEach.call(buttons, function(button) {
        button.addEventListener('click', function(e) {
          e.target.style.backgroundColor = e.target.getAttribute('data-color');
        });
      });

    }
  </script>
</head>

<body onload="initialize()">
  <input type="button" value="button" style="color:white" data-color="#101010" />
  <input type="button" value="button" style="color:white" data-color="#bada55" />
  <input type="button" value="button" style="color:white" data-color="#400400" />
</body>
</html>

Answer №2

If you take a quick glance at the example provided, you'll see how easy it is to change the color of any button using this method:

<input type="button" id="btn1" value = "Button 1" style= "color:blue" onclick="changeColor('btn1', '#FF5733')";/>

<input type="button" id="btn2" value = "Button 2" style= "color:red" onclick="changeColor('btn2', '#FF5733')";/>

The function for changing colors requires two inputs - the ID of the button and the desired color value. So we specify the unique IDs (btn1 and btn2) for each button in this case.

Answer №3

To accomplish this task in JavaScript, you must employ the `this` statement. This allows you to manipulate the specific element that triggered the event.

Check out the following demonstration:

var updateColor = function () {        
    $('.btn').click(function() {
        $(this).css('background-color', 'blue');
    });
};

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 integrating user input from HTML into a JavaScript file to execute a GET request

I am currently working on a project to create a website that integrates the google books API for users to search for books. To start, I have set up a server using express in index.js at the root of the project directory, and all my static files are stored ...

JavaScript function for converting timestamp to readable date

Can someone help me transform the timestamp 1382086394000 into a readable date format 2013-10-18 08:53:14 by using a JavaScript function? The current function I have is: function cleanDate(d) {return new Date(+d.replace(/\/Date\((\d+)\ ...

Executing Enter Key and Button Simultaneously with JavaScript: Step-by-Step Guide

I need assistance understanding how to simultaneously trigger the enter key and button in this code. When the value is entered into the input field, it should trigger both the enter key and the button "Enter" at the same time. Additionally, after pressing ...

Running a <script> tag with an external src attribute in a dynamic manner through the use of eval

Currently, I am utilizing the Genius API to fetch lyrics for a particular song and then embed them within an HTML <div> tag. My interaction with this API is through PHP, employing an AJAX GET request. Upon a successful AJAX request, the following HT ...

Is it possible for Node.js to not automatically restart the server when modifying .js files?

Right now I have node-supervisor set up to detect changes in .js files, and while it works well, I've realized that it restarts the server every time a js file is saved. Is there a way to save a server-side .js file without triggering a server restart ...

Having trouble updating the value of my textfield in material-ui using formik

Below is the code I'm working with to set a default value using the material-ui Textfield API within a formik fieldarray: <TextField name={`myGroups.${index}.myGroupName`} value={`Group ${index+1}`} label="Group" InputProps={{ ...

Error: Unable to retrieve the value of a null property | ReactJS |

There are two textboxes and one button designed as material UI components. </p> <TextField id="chatidField" /> <br /> <p> <code>Enter Your Name:</code> <hr /> & ...

There are no functions or classes returned when using NPM Link with the module

Welcome. Whenever I run npm link ../folder/ToFolder, it works as expected. However, when I attempt to import any function, nothing is returned. A clearer explanation I have tried importing a module that I created from another folder using npm link. When ...

Transform an object into an array using JavaScript with the help of Lodash, Azure Functions, and Azure Logic Apps

To achieve the desired result of extracting JSON from a proprietary content management system, transforming it into a CSV, and depositing that CSV in an Office 365 shared drive, a combination of Azure Function and Azure Logic App is utilized. The Node/Java ...

Hover over a particular element using a loop in Vue.js

Is there a way to change the price button to an Add to Cart button on mouseover, considering the true false data trigger for each item? How can we specify which item to target when hovering over the price section? Below is the code snippet: template: < ...

While it is possible to filter by friend.brand.id within friends in Angular, unfortunately the || undefined trick cannot be used to reset the filter when it is NULL

In the futuristic world of 2075, immortal humans have subjugated mortal humans. There exists a unique store where mortal friends are sold, and efforts are being made to develop an app that allows customers to manage their friends based on their favorite br ...

Ways to retrieve information from a URL using the .get() method in a secure HTTPS connection

As I work on handling user input from a form using node.js, express, and bodyParser, I encounter an issue. Even after using console.log(req.body), the output is {}. This is puzzling as there is data in the URL when the form is submitted successfully at htt ...

Update Material-ui to include an inclusive Datepicker widget

I have integrated the Material-ui Datepicker into my website to allow users to download timed event information from a database. The issue I am facing is that when users select two bracketing dates, events for the end date are not showing up correctly. F ...

I am encountering an issue with opening a dropdown select option upon clicking in C# while using Selenium

I am encountering an issue while attempting to open the Register page from my account. The UI developer utilized Bootstrap code, and Bootstrap developers have included a JS function on click. However, when I execute this code, an error is thrown: "OpenQA.S ...

How can I add a character at a precise location while keeping the existing tags intact

Latest Update After further testing, it seems that the code performs well with a faux spacer, but runs into issues with the regex. The following scenarios work correctly: Selecting words above or below the a tag Selecting just one line directly above or ...

Display a popup notification when clicking in Angular 2

Can anyone help me with displaying a popup message when I click on the select button that says "you have selected this event"? I am using Angular 2. <button type="button" class="button event-buttons" [disabled]="!owned" style=""(click)="eventSet()"&g ...

Having trouble with installing Recharts through npm

When I try to install recharts using npm, I encounter the following error message in my console: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! ...

Changing the theme of a toggle button in Jquery Mobile when the button is pressed

I have a group of buttons with a specific class <div class="prog-day"> <div class="prog-clear" data-role="controlgroup" data-type="horizontal> <a href="#" data-role="button" data-mini="true" data-theme="b">Clear</a> ...

Issue: Access to sdcard/hello.mp3 file denied due to permission error (EACCES)

While testing the "react-native-audio-recorder-player": "^3.5.3" on Android 11 & 12 with targetSDKversion 31, I encountered the error message Error: sdcard/sound.mp3: open failed: EACCES (Permission denied). Numerous suggested solut ...

Is it a cookie-cutter function?

Can someone help me solve this problem: Implement the special function without relying on JavaScript's bind method, so that: var add = function(a, b) { return a + b; } var addTo = add.magic(2); var say = function(something) { return something; } ...