Reputation: 51
I want to change class of element, everytime I click on it.
on css section I have:
myButton.btn_first_look {
/* some atributes */
}
myButton.btn_second_look{
/* some atributes */
}
little jquery:
$(document).ready(function(){
$('#myButton').click(function() {
$(this).toggleClass('btn_first_look');
$(this).toggleClass('btn_second_look');
})};
So, when I click on element, I expect jquery script to change element class from btn_first_look
to btn_second_look
and otherwise.
But boom. Nothing happend
Upvotes: 0
Views: 1573
Reputation: 6351
Use removeClass()
and addClass()
respectively
$('#myButton').click(function() {
//if button has class btn_first_look
if($(this).hasClass('btn_first_look')){
$(this).removeClass('btn_first_look');
$(this).addClass('btn_second_look');
}
//if button has class btn_second_look
else if($(this).hasClass('btn_second_look')){
$(this).removeClass('btn_second_look');
$(this).addClass('btn_first_look');
}
});
This adds whichever class the button doesn't have, and removes the class it does.
Upvotes: 1
Reputation: 9947
toggleClass
will take care of add and remove by itself
$('#myButton').click(function() {
$(this).toggleClass('btn_second_look btn_first_look');
};
Upvotes: 1
Reputation: 2422
That will work for you
$(document).ready(function(){
$('#myButton').click(function(){
$(this).toggleClass('btn_first_look btn_second_look');
});
});
Upvotes: 0
Reputation: 152
Add a parenthesis at the very end. Your first (function()
has no close, so it won't work.
Upvotes: 0
Reputation: 3456
Try this.
If your element has class btn_first_look
from the start, you can write
$(element).toggleClass("btn_first_look btn_second_look");
This will remove class btn_first_look
and add class btn_second_look
. If you do that again, it will remove class btn_second_look
and reinstate class btn_first_look
.
Upvotes: 0