简体   繁体   中英

remove css style on button click jquery?

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.

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

$('.mybtn').toggle(function () {
    $(".mybtn").removeClass("mybtn").addClass("expand");
}, function () {
    $(".mybtn").removeClass("expand").addClass("mybtn");
});

try this :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM