I have a button with the class add-to-favorite when clicked the class is changed to remove-from-favorite and a file is added to favorite. When the user clicks on the button again, it has remove-from-favorite The class is changed to add-to-favorite and the file must be removed from the favorite, but this is not the case. The button acts like the remove-from-favorite even if the class is add-to-favorite;. Any ideas?
Here is the code :
<button type="button" class="add-to-favorite" name="button"><i class="material-icons">favorite_border</i></button>
Here is the Javascript code for add-to-favorite
$(".add-to-favorite").on("click", function(event) {
var clicked_button = $(this);
clicked_button.html("<i class='material-icons'>close</i>");
clicked_button.removeClass('add-to-favorite');
clicked_button.addClass('remove-from-favorite');
})
Here is javascript for remove-from-favorite
$(".remove-from-favorite").on("click", function(event) {
var clicked_button = $(this);
clicked_button.html("<i class='material-icons'>favorite_border</i>");
clicked_button.removeClass('remove-from-favorite');
clicked_button.addClass('add-to-favorite');
})
Advertisement
Answer
Just use $(document).on() for click event:
$(document).on("click",".add-to-favorite", function(event) {
var clicked_button = $(this);
clicked_button.html("<i class='material-icons'>close</i>");
clicked_button.removeClass('add-to-favorite');
clicked_button.addClass('remove-from-favorite');
});
$(document).on("click",".remove-from-favorite", function(event) {
var clicked_button = $(this);
clicked_button.html("<i class='material-icons'>favorite_border</i>");
clicked_button.removeClass('remove-from-favorite');
clicked_button.addClass('add-to-favorite');
});