Reputation: 143
I want to toggle my button by switching class
<button type="button" class="btn btn-success btn-sm btn-edit">
<span class="glyphicon glyphicon-edit"></span> // default class is glyphicon edit
</button>
JS:
$('.btn-edit').click(function() {
$(this).children().removeClass('glyphicon-edit').addClass('glyphicon-ok');
});
But when I clicked again is's doesn't comeback on glyphicon-edit
class
Upvotes: 0
Views: 65
Reputation: 115212
You can use toggleClass()
for toggling class.
Description: Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the state argument(taken from http://api.jquery.com/toggleclass/).
$('.btn-edit').click(function() {
$(this).children().toggleClass('glyphicon-edit glyphicon-ok');
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button type="button" class="btn btn-success btn-sm btn-edit">
<span class="glyphicon glyphicon-edit"></span>
</button>
Upvotes: 1
Reputation: 15555
$('.btn-edit').click(function() {
$(this).children().toggleClass('glyphicon-edit glyphicon-ok');
});
.glyphicon-edit{color:red}
.glyphicon-ok{color:blue}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="btn btn-success btn-sm btn-edit">
<span class="glyphicon glyphicon-edit">edit</span>
</button>
Use .toggleClass()
Description: Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the state argument.
Upvotes: 0