My application has several buttons (say b1,b2,b3) which I am using as navigation menu items (alternate to using <a>
). I want to change the color of the button when it is clicked/selected. When a particular button is clicked (say b1), its color should change to say red
and all b2,b3 should have color grey
. When b2
is selected, it should be red and b1
should switch back to grey
. Is there a way I can do so using css
and pseudo
elements (something similar to :hover
)?
Asked
Active
Viewed 197 times
0

Manu Chadha
- 15,555
- 19
- 91
- 184
-
Pretty sure this is not possible with css only.. You'll need javascript to do this. – Bryan Elliott Jan 24 '20 at 02:40
-
1Does this answer your question? [How to keep :active css style after click a button](https://stackoverflow.com/questions/31178653/how-to-keep-active-css-style-after-click-a-button) – Dylan Anlezark Jan 24 '20 at 02:45
1 Answers
-1
A good strategy is to have a class isClicked
which have the styles of the clicked element, and toggle everytime the element is clicked,say:
I use jquery to show the logic behind it :D
$('div').click(function(){
$('div.isClicked').toggleClass('isClicked')
$(this).toggleClass('isClicked')
})
div {
width: 100px;
margin:10px auto;
cursor: pointer;
text-align:center;
background-color:grey;
}
div.isClicked {
background-color:red !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>A</div>
<div>B</div>
<div>C</div>

Shan Surat
- 304
- 4
- 13
-
-
@volt It's not possible with just the tagged languages so there's not really any harm in introducing an arbitrary 3rd option. – TylerH Jan 24 '20 at 03:39
-
I understand and agree @TylerH but why load jQuery for this when it's possible with vanilla JS? – volt Jan 24 '20 at 03:41
-
@volt Probably because Kristian prefers jQuery. Or because it's more complicated in vanilla JS. Or some other reason. Take your pick. – TylerH Jan 24 '20 at 14:38