Reputation: 553
I have a button called button1 that I want changed to button2 after a click.
.button1 {
background-image: url("example.com");
}
.button2 {
background-image: url("example2.com");
}
The link looks like this:
<%= link_to example_path do %>
<div class="button1"></div>
<% end %>
and the jquery looks like this:
$(document).ready(function(){
$('.button1').click(function(){
$(this).toggleClass(".button2");
});
});
Nothing is happening though when I click it.
Upvotes: 1
Views: 1378
Reputation: 9690
Just so there's no conflict between the two classes:
$(document).ready(function(){
$('.button1').click(function(){
$(this).removeClass("button1").addClass("button2");
});
});
If you choose to go this route, I would recommend putting an identifier on the button that is not related to the class containing the background-image attribute.
<%= link_to example_path do %>
<div class="mybutton button1"></div>
<% end %>
then you could do this:
$(document).ready(function(){
$('.mybutton').click(function(){
$(this).toggleClass('button1 button2');
});
});
Unless, of course, you do not want to be able to toggle the button back once you click it, in which case the first code sample in this post would suffice.
Upvotes: 1
Reputation: 800
Remove the leading . in the toggleClass line:
$(document).ready(function(){
$('.button1').click(function(){
$(this).toggleClass("button2"); //NOT .button2
});
});
Upvotes: 1
Reputation: 2064
here a better way to do it in CSS;
.button1 {
background-image: url("example.com");
}
.button1:active {
background-image: url("example2.com");
}
Upvotes: 2