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

Retrieve JSON Object using a string identifier

I created a script that takes the ID of a link as the name of a JSON dataset. $('.link').click(function() { var dataset = $(this).attr("id"); for (var i = 0; i < chart.series.length; i++) { chart.series[i].setData(lata.dataset ...

Using jQuery to load a text file and dynamically insert it into a specified div

How can I load a *.txt file and insert the content into a div? Here is my code: JavaScript: $(document).ready(function() { $("#load").click(function() { $.ajax({ url : "file.txt", success : function (data) { ...

Creating a personalized layout for your WordPress posts with custom card designs

As a new developer diving into the world of WordPress, I am aiming to create a sleek and minimalistic grid/card layout for my website. Struggling to achieve this, I seek guidance on how to replicate the design seen in the following link: desired result H ...

Troubleshooting a Problem with CSS Div Multi-column Formatting

I have designed a multi-column div that displays correctly in Firefox but has formatting issues in Chrome and IE. In Firefox, the three columns appear properly with the frame of the last item in column one ending correctly. However, in Chrome and IE, the f ...

Tips for adjusting the Material UI Tabs indicator's position with react-scroller

My customized MaterialUI Tabs component stacks all tab content for scrolling using react-scroller. The tabs work smoothly except the indicator does not update its position. The react scroller has props like onSetActive, onSetInactive, and activeClass whic ...

Unable to download and install jspdf version 1.5.3

Currently, I am facing an issue where I need to convert HTML to PDF using jspdf 1.5.2. However, I am encountering an error that says "Cannot read property 'charAt' of undefined" when trying to utilize html2canvas. When attempting to upgrade to j ...

Tips for validating and retrieving data from a radio button paired with an input box in reactjs

I'm diving into the world of React and facing a challenge with multiple radio buttons that have associated input fields, like in this image: https://i.stack.imgur.com/Upy3T.png Here's what I need: If a user checks a radio button with a ...

Utilizing JQuery to modify the element's id and trigger a function upon clicking

There is an element with a specific ID that I have changed. However, even after changing the ID and clicking on the element with the new ID, it still triggers the function associated with the old ID. $('#1st').click(function(){ $('#1s ...

Adjusting the color of the legend on a LineChart in ExtJS 4 on-the-fly

I've been trying to find information on how to modify the color of the x legend in a Line chart without success. Can anyone help me with this? I have included an image of the chart for reference. ...

Designing the autocomplete dropdown feature in Bootstrap UI

I'm currently developing an app that is utilizing AngularJS and Bootstrap, with the assistance of Bootstrap UI. Specifically, I am working on implementing the typeahead feature. However, I am facing a challenge in trying to ensure that the dropdown li ...

When attempting to use Ajax, the operation fails; however, if I directly access the URL,

When using firebug, I attempted to make the following AJAX call: var rootUrl = 'http://172.24.105.22:8080/geoserver/Chennai_Sub/ows'; var defaultParameters = { service: 'WFS', version: '1.0.0', request: 'Get ...

The inclusion of float: left disrupts the formatting of the list

My webpage features a visual element known as a "plan", which consists of a small table and an image. I want these two elements to appear side by side without any styling. Currently, they are displayed one below the other. You can view how it looks like he ...

Maximizing PUT Methods in HTTP RESTful Services

I've been playing around with my routes file and I'm looking to switch up the method being called (delete instead of update). Code Snippets: # User management API GET /users @controllers.Users.findUsers POST /user ...

Creating a route-guard in a Vue.js/Firebase authentication system for secure navigation

I have created a Vue.js/Firebase authentication interface following a tutorial. The app is mostly functioning properly, but I am experiencing issues with the route guard. Upon signing in and redirecting from "http://localhost:8080/home" to "http://localh ...

The functionality of RegExp is not as expected in this specific case, even though it works correctly in all

I am new to Node.js and currently transitioning from a PHP background, eager to learn more about it. My challenge involves using the following Regular Expression: /([A-Z]{2,})+/gim (identifying two or more consecutive letters). The string I am working w ...

The basic evaluation of jQuery elements does not result in a comparison

Wondering what's going wrong in this code: employee_ids = $('[data-employee_id="'+employee+'"]'); timestamp_ids = $('[data-scheduled_on="'+timestamp+'"]'); var common = $.grep(timestamp_ids, function(element) ...

What is the reason that certain functionalities do not work on an element that has two CSS classes assigned to it

I have a unique situation with two input elements and a button: <input class="close-acc-usr opt-in" type="text" name="closeAccUsr" /> <input class="close-acc-pin opt-in" type="number" name="cl ...

Error: Trying to use 'setTimeout' before it has been initialized is not allowed

I'm currently working on a JavaScript exercise in my code. I encountered an issue where I am trying to assign a reference to the setTimeout function to ogTimeout on the second line since I plan to redefine setTimeout later. However, when I run the co ...

Update the logo for mobile, desktop, and tablet display using Bootstrap 4alpha

I am currently working on customizing a header with Bootstrap 4 alpha. <div class="container"> <div class="row"> <div class="col-md-6 text-md-left text-center"> <div class="navbar-brand"><img src="/wp-con ...

``It seems like the Tailwind background image is not appearing on

The issue lies in the background image not displaying despite trying different methods such as using ""bg-[url('/image/example.jpeg')"" tailwind.config.js theme: { extend: { colors: { darkBlue: "#0 ...