23

I am using bootstrap 3. I want to change button color when I click on button.I mean button should be in different color when it is selected. How can I do this using css?

My codes are :

<div class="col-sm-12" id="">
    <button type="submit" class="btn btn-warning" id="1">Button1</button>
    <button type="submit" class="btn btn-warning" id="2">Button2</button>
</div>
amphetamachine
  • 27,620
  • 12
  • 60
  • 72
Priyank Dey
  • 1,104
  • 1
  • 19
  • 43

3 Answers3

57

CSS has different pseudo selector by which you can achieve such effect. In your case you can use

:active : if you want background color only when the button is clicked and don't want to persist.

:focus: if you want background color untill the focus is on the button.

button:active{
    background:olive;
}

and

button:focus{
    background:olive;
}

JsFiddle Example

P.S.: Please don't give the number in Id attribute of html elements.

Community
  • 1
  • 1
Sachin
  • 40,216
  • 7
  • 90
  • 102
8

CSS has many pseudo selector like, :active, :hover, :focus so you can use.

.btn{
    background: #ccc;
} .btn:focus{
    background: red;
}
<div class="col-sm-12" id="my_styles">
<button type="submit" class="btn btn-warning" id="1">Button1</button>
<button type="submit" class="btn btn-warning" id="2">Button2</button>
        </div>
JsFiddle
AliNajafZadeh
  • 1,216
  • 2
  • 13
  • 22
Ali Haider
  • 179
  • 1
  • 1
  • 8
4

HTML--

<div class="col-sm-12" id="my_styles">
   <button type="submit" class="btn btn-warning" id="1">Button1</button>
   <button type="submit" class="btn btn-warning" id="2">Button2</button>
</div>

css--

.active{
         background:red;
    }
 button.btn:active{
     background:red;
 }

jQuery--

jQuery("#my_styles .btn").click(function(){
    jQuery("#my_styles .btn").removeClass('active');
    jQuery(this).toggleClass('active'); 

});

view the live demo on jsfiddle

Sarower Jahan
  • 1,445
  • 1
  • 13
  • 20
  • A little late maybe, but I find your answer more appropriate than the rest. I viewed the jsfiddle. But I am having trouble as to how I should include it in my program. Is there anything I need to import? It worked fine on the fiddle, not in my program though. I placed the jquery in the ` – Harshith Rai Sep 17 '18 at 06:50
  • Check browser console message. make sure you have loaded jquery before above jquery – Sarower Jahan Sep 20 '18 at 21:42