1

I am trying to change the colour of buttons if they're clicked using jquery.

my code bellow works and it will add the expand class to the clicked button. but I need to know how I can remove the class and add the old class to it if another button is clicked and visa versa.

this is my code now:

$(".mybtn").click(function(){
  $(this).removeClass( "mybtn" ).addClass('expand');

});  

and the html is like this:

<button name='mybtn' id='mybtn' class='mybtn' value='1'>1</button>
<button name='mybtn' id='mybtn' class='mybtn' value='2'>2</button>
<button name='mybtn' id='mybtn' class='mybtn' value='3'>3</button>

and the css is a simple css with background color:

.mybtn{
background-color:#fff;
}

.expand{
background-color:#000;
}

any help would be appreciated.

2
  • FYI IDs must be unique. Commented Jul 11, 2014 at 16:39
  • Are you trying to achieve a toggle effect on click? Commented Jul 11, 2014 at 16:41

3 Answers 3

1

Reset all the "expand" class objects first:

$(".mybtn").click(function(){
   // remove expand class and add original mybtn class
  $(".expand").removeClass( "expand").addClass("mybtn");

  $(this).removeClass( "mybtn" ).addClass('expand');

}); 

See working example at Fiddle

Sign up to request clarification or add additional context in comments.

4 Comments

this is exactly what I needed to do. Thank you Jim.
FYI: You can get the same results without ever removing the "mybtn" class
@user3806613, please mark this one as the right answer if it worked for you :)
@entiendoNull, I did try to do that but STO says I have to wait for 5 minutes before accepting the answer. it is now 2 minutes. so will accept it as soon as the time limit is up.
0
$('.mybtn').toggle(function () {
    $(".mybtn").removeClass("mybtn").addClass("expand");
}, function () {
    $(".mybtn").removeClass("expand").addClass("mybtn");
});

Comments

0

try this :

$(".mybtn").each(function(){    
   $(this).click(function(el, ev){
      $('button#mybtn').addClass('mybtn').removeClass('expand'); 
      $(this).removeClass( "mybtn" ).addClass('expand');     
   }); 
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.