I\'m trying to have the span, on click, toggle its classes between .btn-warning
and .btn-primary
. However, my code only works for the first click. Ever
Changing the class does not magically add the events that were previously added. You either need to unbind/bind the events once again, or use a generic onclick handler that knows how to handle it, or use event delegation.
All that code could be reduced to:
$(".btn").on("click", function() {
$(this).toggleClass('btn-warning').toggleClass('btn-primary');
});
.btn-primary { background-color: blue; }
.btn-warning { background-color: yellow; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class="btn btn-warning" >Click me</span>
You need to use event delegation method because you're binding event to dynamically added class element:
$(document).ready(function(){
$(document).on('click','.btn-warning',function(){
$(this).removeClass('btn-warning').addClass('btn-primary');
});
$(document).on('click','.btn-primary',function(){
$(this).removeClass('btn-primary').addClass('btn-warning');
});
});
Simply you may do like this:
$(document).on("click",".btn", function() {
$(this).toggleClass('btn-warning btn-primary');
});