When the mouse is released, modify the button

Looking for assistance with changing the background color of a button when clicked, without any post back. I have multiple buttons and want only the clicked one to change color while the others stay the same. Any suggestions on how to achieve this?

Answer №1

Here's one way to achieve the desired effect:

<style>
.selected { background-color : red; }
</style>
<script>
var form = document.getElementById("targetForm");
form.onclick = function(event) {
    // Consider compatibility with IE
    if (!event) event = window.event;

    var element = event.srcElement || event.target;

    if (element.tagName.toLowerCase() === "input"
        && element.type.toLowerCase() === "button"){
        element.className = "selected";
        
        for (var i = 0; i < form.children.length; i++) {
            if (element != form.children[i]) {
                form.children[i].className = "";
            }
        }
    }             
};
</script>

See it in action: http://jsfiddle.net/Yn3pT/

This code assumes that the buttons are within a form named "targetForm" and that there is a class called "selected" that defines the desired color - feel free to adjust this according to your HTML structure.

Remember to place this script either within an onload handler or after the elements in the source for proper execution.

Additionally, using onclick instead of onmouseup may be more suitable for this scenario.

Answer №2

<button class="mouseup"> Press here </button>
<button class="mouseup"> Press here </button>
<button class="mouseup"> Press here </button>

$buttons = document.getElementsByClassName('mouseup');

for(var i = 0; i < $buttons.length; i++ ) {
    $buttons[i].onmouseup= function(){
        this.style.background = 'red';  
        for(var j = 0; j < $buttons.length; j++ )
            if( $buttons[j] != this ) 
                $buttons[j].style.background = '#EFEFEF'; 
     }
}   

http://jsfiddle.net/nQHup/6/

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

Submitting information in a Node.js application

I'm encountering an issue with posting data from an HTML file to my Node app. Here's the relevant code snippets: <form method="post" action="localhost:3000/post"> <input name="user[name]" type="text"/> <button type="submit"& ...

Different ways to dynamically change tailwind colors during execution

Utilizing tailwind v3, it's feasible to customize existing colors by modifying the tailwind.config file. https://tailwindcss.com/docs/customizing-colors module.exports = { theme: { extend: { colors: { gray: { ...

What steps can be taken to prompt the layout to transition?

I have an element that sticks to the top based on the current scroll offset. The issue is that the layout doesn't update when there is space available after the stuck element. This creates a ghost gap where the stuck element used to be... http://fidd ...

Rendering HTML or links sourced from encoded JSON data with JavaScript

After making an ajax call, I receive the following data: {"dataList":[{"date":"August 27, 2013","text":"<a href=\"http:\/\/www.example.com\/test.aif\" title=\"Click here to listen\" target=\"\">Click her ...

Axios sending a 400 Bad Request to Django due to a missing required field

I'm having issues sending a POST request from my React frontend using Axios. import axios from 'axios' axios.post('http://server:port/auth/login', { username: 'admin', password: 'MY_PASSWORD', }, { ...

What is the official name of the key type for the Built-in Object?

There was a built-in type that I used in the past which represented the union of all possible object keys. It was named objectKey or something similar. Here is an example: type objectKey = string | number | symbol Unfortunately, I am drawing a blank on t ...

Query the Firebase database in Angular2 to locate the latitude and longitude values that are nearest to the user's current coordinates

I am working with a database table named locations, which contains a list of places along with their corresponding lat/long coordinates. Additionally, I am utilizing geolocation to retrieve the user's current lat/long. My goal is to identify the loc ...

Access Vue.js data attribute in jQuery

Is there a way to extract the data-src attribute value from the following HTML code using Vue.js? <img id="some_id" :data-src = "some_path"> I attempted to assign this value to a variable using jQuery: var imgSrc = $("img:data(src)"); Unfortunat ...

Having trouble with installing "npm install semantic-ui-react semantic-ui-css"? Any ideas on how to fix it?

Encountered an error while trying to install Semantic UI React and Semantic UI CSS: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: [email protected] npm ERR! Found: [ema ...

Modify the text color of the fixed navigation when hovering over specific divs

Sorry if this question has already been asked. I've searched online but haven't come across a satisfactory solution. On my website, I have different background colors - blue and white. The text color in my navigation is mostly white, but I want i ...

Guidelines for transferring data when a button is held down or pressed

I am looking to continuously send values while a button is pressed. Currently, a value is only sent with each click. Below is the current code: my_custom_script.js $(document).ready(function() { $('#left').mousedown(function() { var left ...

Modify the class of the focused element exclusively in Angular 2

I'm working on a project that involves several buttons and div elements. Currently, the divs are hidden, but I want to be able to reveal a specific div when its corresponding button is clicked. For example: If you click the first button, only the fir ...

Access-Control-Allow-Origin does not permit the origin null

I've been searching for an answer to this question, but I haven't found a suitable one yet. let xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState === 4 && xhr.status === 200){ let response = r ...

``Using ASP.NET MVC3 to create a dynamic UI with a JQuery dialog that

I'm struggling to wrap my head around the correct approach for this task: Currently, I am developing a basic user membership application that is designed to assign application roles to users. The aim is to create a jQueryUI dialog that contains a Dro ...

I'm encountering an error when trying to use makeStyles

Something seems off with MUI. I was working on my project yesterday and makeStyles was functioning properly, but now it's suddenly stopped working. I'm encountering an error when calling it here: https://i.sstatic.net/tBf1I.png I suspect the iss ...

Troubleshooting imagejpeg() Function Failure in PHP Server

I've been working on implementing image cropping functionality for my website. I've managed to send an array of cropped image dimensions (x, y, width, height) to my PHP script. On my localhost, the script successfully crops the image, but unfort ...

Sorry, the mailbox you are trying to reach is currently unavailable. The server has encountered an issue and is unable to relay your

Having an issue with sending e-mail messages from the AccountController in the same ASP.NET MVC 4 website. Strangely, it works from all other controllers except AccountController. When trying to send an e-mail from the AccountController, I receive the fol ...

What is the best way to restrict the input options for a String field within a TextField component in Material-UI?

When working with Material-UI, how can we set a maximum length restriction for a text field? Below you will find an example of the TextField component: <TextField id="name" label="Name" type="string" //maxLengt ...

ng-repeat hide all elements except the first one

Hello there! I'm currently working on rendering a form based on an API call. Using a couple of filters, I am able to hide all elements that have 'id' in the title and which equal 0. However, I do need to display the initial element Id. I tho ...

Loop through the JSON array and append every value to the list within AngularJS

I'm just starting to learn about Angular JS and I have a question. I receive a JSON array as an AJAX response from a PHP page. I want to iterate through this JSON array and push each value into a list like this: angular.forEach($scope.companies.area, ...