I'm trying to create a Like button with an input with the type image which its src changes when it is hovered/clicked. I want to change it when it is hovered and have its previous source back when it is unhoverd. So I used onmouseover and onmouseout to do this. I also used onclick to the src when it is clicked on.
The problem is that when I click on it, it changes as intended but as soon as I move the mouse so it is not hovered anymore, It calls the onmouseout function and this is not what I need.
Edit: There are multiple buttons so I cant't use a boolean variables to check if was clicked.
What should I do to not execute onmouseout when it was clicked on?
<input type="image" src="path" onmouseover="likeHover(this)" onmouseout="likeUnhover(this)" onclick="like(this, '{{post.id}}')">
function likeHover(btn) {
btn.src = '../../static/network/img/heart-pink.png';
}
function likeUnhover(btn) {
btn.src = '../../static/network/img/heart-black.png';
}
function like(btn) {
btn.src = '../../static/network/img/heart-red-filled.png';
}
You could use a boolean variable, and set it to true if the button was clicked.
And use addEventListener in the JS code and not the HTML attributes:
const input = document.querySelector("input[type=image]");
let clicked = false;
input.addEventListener("mouseover", (e) => {
if (!clicked)
e.target.src = '../../static/network/img/heart-pink.png';
});
input.addEventListener("mouseout", (e) => {
if (!clicked)
e.target.src = '../../static/network/img/heart-black.png';
});
input.addEventListener("click", (e) => {
clicked = true;
e.target.src = '../../static/network/img/heart-red-filled.png';
});
<input type="image" src="path">