Reputation:
I'm working with a button, that stores a number of likes on a post. Code:
<button id="likebtn" type="button"
class="btn btn-sml btn-danger" style="width:70px;">
<i class="glyphicon glyphicon-thumbs-up"> </i>
<?php echo $post_likes; ?>
The problem comes, when I click the button - the like icon disappears. It appears back when I refresh the page. Code.
let likebtn = document.querySelector('#likebtn');
likebtn.addEventListener('click', likes_function => {
//increace likes
likebtn.value = <?php echo $post_likes?> + 1;
likebtn.innerHTML = <?php echo $post_likes?> + 1;
document.getElementById("likebtn").disabled = true;
document.getElementById("likebtn").style.opacity=0.5;
}
});
How can I fix this?
Thank you for your help :)
Upvotes: 1
Views: 44
Reputation: 66425
This is because innerHTML
is replacing the entire contents inside button including the icon. You can wrap likes in a nested element and only replace the contents of that:
<button id="likebtn" type="button" class="btn btn-sml btn-danger" style="width:70px">
<i class="glyphicon glyphicon-thumbs-up"></i>
<span class="likes"><?php echo $post_likes; ?></span>
</button>
// ....
const likeBtn = document.querySelector('#likebtn');
const likeBtnLabel = likeBtn.querySelector('.likes')
likeBtn.addEventListener('click', () => {
// Increase likes.
likeBtn.value = <?php echo $post_likes?> + 1;
likeBtnLabel.innerText = <?php echo $post_likes?> + 1;
likeBtn.disabled = true;
likeBtn.style.opacity = 0.5;
});
P.S. likes_function
does not name your function, instead you named the first argument of the click function "likes_function", which is a mouse event object
Also note I changed innerHTML
to innerText
for security reasons since you only need to change text and not html.
Upvotes: 1