I am running rails 3.1 and have the following jquery script in a file /app/assets/javascripts/procedures.js.
$(document).ready(function(){
$('.unselected').click(function() {
$(this).removeClass('unselected');
$(this).addClass('selected');
});
$('.selected').click(function() {
$(this).removeClass('selected');
$(this).addClass('unselected');
});
});
The first action works as expected (selecting), but unselecting does not work.
On the other hand, this script works as expected.
$(document).ready(function(){
$('.tile').click(function () {
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
$(this).addClass('unselected');
} else if ($(this).hasClass('unselected')) {
$(this).removeClass('unselected');
$(this).addClass('selected');
}
});
});
Is it because event listeners are only assigned when the script is first run?
Adding the class
.unselectedto an element after binding to that click handler wont affect the new elements with that class. you have to use jQuery.on()to bind to all.unselectedelements, current and future. http://api.jquery.com/on/Change your
.click()s to be like this, for both.selectedand.unselected: