Izir Atig Izir Atig - 2 months ago 13
Javascript Question

How I keep clicked button light up till I click another button?

I'm about to make row of buttons as menu bar and I'd like them to behave like I want. So lets say there is buttons

A
,
B
,
C
and
D
. If I click for example button
B
I want it to light up and stay light up till I click another button (
A
,
C
or
D
). This kind of idea. I'm pretty sure it's not new one. And I believe there is more sophisticated way to do it than my version below.
I also want page to roll up on every button click.

$('#abutton').click(function() {
$('#abutton').removeClass('off').addClass('on');
$('#bbutton').removeClass('on').addClass('off');
$('#cbutton').removeClass('on').addClass('off');
$('#dbutton').removeClass('on').addClass('off');
window.scrollTo(0,0);
});

$('#bbutton').click(function() {
$('#abutton').removeClass('on').addClass('off');
$('#bbutton').removeClass('off').addClass('on');
$('#cbutton').removeClass('on').addClass('off');
$('#dbutton').removeClass('on').addClass('off');
window.scrollTo(0,0);
});

$('#cbutton').click(function() {
$('#abutton').removeClass('on').addClass('off');
$('#bbutton').removeClass('on').addClass('off');
$('#cbutton').removeClass('off').addClass('on');
$('#dbutton').removeClass('on').addClass('off');
window.scrollTo(0,0);
});

$('#dbutton').click(function() {
$('#abutton').removeClass('on').addClass('off');
$('#bbutton').removeClass('on').addClass('off');
$('#cbutton').removeClass('on').addClass('off');
$('#dbutton').removeClass('off').addClass('on');
window.scrollTo(0,0);
});

Answer

Use classes

$('.button').click(function(){
    $('.button').removeClass('on').addClass('off');
    $(this).addClass('on').removeClass('off');
});

fiddle

Comments