Serhiy Serhiy - 1 month ago 7
CSS Question

How to change background color when button or div pressed and if pressed another one the first one changes color back?

I have list of buttons (or div):

<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>

I want to have next:

when I press btn1 it's background color changes to white. When I press btn2 - btn2 background color becomes white and btn1 background color changes back to normal.


Another solution, still using jQuery :


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


function activate( element ){
    $( element ).addClass( 'active' );

function clearAll(){
    $( '.btn' ).removeClass( 'active' );

And a solution using AngularJS :


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

  $scope.activate = function( str ){
    $scope.activeBtn = str;


<div ng-controller="WhiteButtonCtrl">
  <button ng-repeat="button in buttons" ng-class="{ 'active' : activeBtn === }"
          ng-click="activate( )" type="button" class="btn" id="{{}}">