Serhiy Serhiy - 3 months ago 12
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.

Answer

Another solution, still using jQuery :

HTML

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

JS

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

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

https://jsfiddle.net/33eup40e/6/

And a solution using AngularJS :

JS

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;
  }
});

HTML

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

https://jsfiddle.net/33eup40e/13/