What is the process for changing the background color when a button or div is pressed, and reverting the color back when another button or div is

Looking to customize a list of buttons or divs in your project? Check out this sample layout:

<button type="button" class="btn" id="btn1">Details1</button>
<button type="button" class="btn" id="btn2">Details2</button>
<button type="button" class="btn" id="btn3">Details3</button>
<button type="button" class="btn" id="btn4">Details4</button>

Here's the idea:

Clicking on btn1 changes its background color to white. Subsequently, clicking on btn2 turns its background color to white while restoring btn1 back to its original color.

Answer №1

Here's an alternative approach that utilizes jQuery:

HTML

<button type="button" class="btn" id="btn1" onClick="toggleActive( this )">Details1</button>
<button type="button" class="btn" id="btn2" onClick="toggleActive( this )">Details2</button>
<button type="button" class="btn" id="btn3" onClick="toggleActive( this )">Details3</button>
<button type="button" class="btn" id="btn4" onClick="toggleActive( this )">Details4</button>

JS

function toggleActive( element ){
    deactivateAll();
    $( element ).addClass( 'active' );
}

function deactivateAll(){
    $( '.btn' ).removeClass( 'active' );
}

Check out the demo here.

Additionally, here's a solution using AngularJS:

JS

angularApp.controller( 'ButtonController', function( $scope ){
  $scope.buttons = [
    { id: 'btn1', value: 'Details1' },
    { id: 'btn2', value: 'Details2' },
    { id: 'btn3', value: 'Details3' },
    { id: 'btn4', value: 'Details4' }
  ]
  $scope.activeBtn = undefined;

  $scope.toggleActive = function( str ){
    $scope.activeBtn = str;
  }
});

HTML

<div ng-controller="ButtonController">
  <button ng-repeat="button in buttons" ng-class="{ 'active' : activeBtn === button.id }"
          ng-click="toggleActive( button.id )" type="button" class="btn" id="{{button.id}}">
    {{button.value}}
  </button>
</div>

View the AngularJS implementation here.

Answer №2

Develop a CSS style that includes a background color. Afterwards, set up an event listener for each division; when clicked, the unique style should be applied to them. Upon clicking a division, ensure that the style is removed from all other divisions before being added to the selected one.

Answer №3

Obtain your button collections using the document.getElementsByClassName method and capture clicks with the addEventListener function. You can also modify the CSS background by utilizing the element.style.background

<button type="button" class="btn" id="btn1">Details1</button>
<button type="button" class="btn" id="btn2">Details2</button>
<button type="button" class="btn" id="btn3">Details3</button>
<button type="button" class="btn" id="btn4">Details4</button>
<script>
var btn = document.getElementsByClassName("btn");    
 for(var i =0 ; i < btn.length;i++){        
        btn[i].addEventListener("click",function(){
            toggle(this.id);            
        });        
    }
 function toggle(id){
    for(var i =0 ; i < btn.length;i++){
    btn[i].style.background = "";
    }
    document.getElementById(id).style.background = "white";
  }
  </script>

Answer №4

It's as simple as two lines of code to solve your issue

$('.btn').click(function() {
    $('.btn').removeClass('active');
    $(this).addClass('active');
});
.btn {
  background-color: lightblue;
  border: none;
  cursor: pointer;
}
.btn.active {
  background-color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="btn" id="btn1">Details1</button>
<button type="button" class="btn" id="btn2">Details2</button>
<button type="button" class="btn" id="btn3">Details3</button>
<button type="button" class="btn" id="btn4">Details4</button>

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

The frequency of database updates exceeds expectations - involving vue.js this.$router.push and express operations

Having some trouble updating a MongoDB with this code. It seems to be updating three times instead of just once due to having three dates in the posts.date field. Utilizing Vue, Mongo, and Express for this project, I have the following data structure: { ...

Using a JavaScript "for each" loop instead of having several "if

Could you please provide guidance on where to proceed? There are multiple input rows, with each row containing a field with the class row_changed If the value in the field is greater than 0, ajax will send the entire row to PHP. Each row is wrapped in a ...

Can anyone provide guidance on how to calculate the total sum of a JavaScript array within an asynchronous function?

Currently, I am working with Angularjs Protractor for end-to-end testing and faced an issue while trying to calculate the sum of values in a column. Although I am able to print out each value within the loop successfully, I am struggling to figure out ho ...

Create a box with borders and divisions using HTML

Hello, I am trying to create a box in HTML with a slanted divider line inside. How can I achieve this design? I am aiming to replicate the layout shown in this image: Link to Image I have tried implementing the code below, but the alignment is not matchi ...

Prevent Child Elements from Overstretching Container with Bootstrap Flex

I'm working on a layout where all elements can be viewed without the need for scrolling. Any panels that require more space should be scrollable. In the following example, I want the contents of main-left to be scrollable without stretching the entire ...

Is there a way to insert a label directly following a dropdown menu within the same table cell?

My goal is to include drop-down lists in a web page, so I decided to create a table structure using JavaScript. Firstly, I used the document.createElement() method to generate a table, table body, rows, and cells. Then, I proceeded to create select element ...

Guide on building a personalized button layout in Bootstrap 4

I have been working on a React component that I want to stick to the bottom of the screen no matter what content is above it. Even if there is minimal content, I want it to remain at the bottom. To achieve this, I added style={{position: 'fixed' ...

Create a circle-shaped floor in THREE.JS that mimics the appearance of a shadow

I am working on creating a circle mesh with a gradient material that resembles a shadow effect. Specifically, I want the circle to have a black center and fade to almost white at the edges. Currently, I have been able to create a circle and position it co ...

Error: The function `this.xhr_.upload.addEventListener` is not supported in Firebase Storage

Having some trouble with file uploads. Small files work fine, but when it comes to larger ones I keep getting this error: this.xhr_.upload.addEventListener is not a function. I'm currently using vue.js along with the firebase 6.1.0 npm package. Th ...

Issues arise when the Angular controller fails to load

I'm experiencing an issue with my Angular controller where the code inside its constructor is not running. Here's a snippet of the relevant pieces: conversationcontrollers.js: var exampleApp = angular.module('exampleApp',[]); console ...

No content sent in the request body while implementing fetch

Attempting to send graphql calls from a React component to a PHP server using the fetch method for the first time. The setup involves React JS on the client-side and Symfony 4 on the server-side. Despite indications that data is being sent in the browser ...

The voting system will increase or decrease by 1 to 5 during each round

Recently, I added a voting system to my website inspired by this source. It's functioning well, but there is an issue where each vote can sometimes count for more than one. You can view the source code on the original website and test it out live here ...

Error: Trying to assign a value to a null property

I am facing an issue while trying to dynamically create "iframe's textarea" and insert the value of a variable. Unfortunately, I keep encountering an error. Any suggestions on how to resolve this problem? P.S: Using Google Chrome as the browser ...

Python script to extract data from websites containing javascript and script tags

I'm currently in the process of scraping a javascript-based webpage. After reading through some discussions, I was able to come up with the following code snippet: from bs4 import BeautifulSoup import requests website_url = requests.get('https:// ...

How can Express JS be configured to make URL calls from a local environment?

I encountered an issue with my code (Weather App using OpenWeatherMap Api) when I attempted to move my apiKey and apiUrl to the .env file. An error appeared in the terminal, but it's unclear why it occurred. Below is my code: const express = require( ...

HTML counterpart to PHP's include for JavaScript components

I am searching for a Javascript alternative to a method I have been using in PHP. Specifically, I want to streamline the basic setup of my pages: <!DOCTYPE html> <html lang="en"> <head> <meta ch ...

Updating divs automatically using Ajax without refreshing the page is not functioning as intended

I'm having trouble understanding why this isn't functioning properly. My goal is to have the data from load.php displayed in the div sample. However, if the code is updated (for example, when pulling information from a database), I want only the ...

What is the best way to align an equal number of divs in each row?

I need help arranging my divs in rows, with 3 divs in each row. Can someone assist me with this? Here is the code I have written so far: .container { display: flex; flex-wrap: wrap; } .item { border: 2px solid black; width: 100px; height: 10 ...

Conditional jQuery actions based on the selected radio button - utilizing if/else statements

This task seemed simple at first, but I quickly realized it's more challenging than expected. Apologies in advance, as Javascript is not my strong suit. My goal is to have the main button (Get Your New Rate) perform different actions based on whether ...

Switching the WordPress dropdown menu from a hover function to a click function

Is it possible to modify the WordPress menu dropdown behavior from hover to onclick? I want the menu to appear when an item is clicked, but WordPress currently requires hovering. Below is what I've tried so far, but it has not been successful. Jquery ...