Now it is possible to click on the topleft corner of the image then it is changing. What I want to do is that when the mouse comes over that specific part of the image the pointer cursor will be active. How can I fix this?
let col = document.querySelectorAll('img#lights-on,img#lights-off');
document.addEventListener("click", function(e) {
if (
e.target instanceof HTMLImageElement &&
e.offsetX >= 0 &&
e.offsetX <= 100 &&
e.offsetY >= 0 &&
e.offsetY <= 20) {
col.forEach(img => {
if (img && img.nodeType == 1) {
img.style.display =
( img.style.display == '' || img.style.display == 'block' ) ?
'none' : 'block';
}
})
}
});
img {
width: 300px;
border: 1px solid black;
}
<img
id="lights-off"
src="//www.collinsdictionary.com/images/thumb/apple_158989157_250.jpg"
style="display: none;">
<img
id="lights-on"
src="//upload.wikimedia.org/wikipedia/commons/thumb/8/8a/Banana-Single.jpg/680px-Banana-Single.jpg">
CodePudding user response:
Just you can add a mousemove event
to the document like you did with the click event
but add an else
statement to remove the cursor if it's not in the place you want:
document.addEventListener("mousemove", function(e) {
if(
e.target instanceof HTMLImageElement &&
e.offsetX >= 0 &&
e.offsetX <= 100 &&
e.offsetY >= 0 &&
){
document.body.style.cursor = "pointer"
}
else{
document.body.style.cursor = ""
}
})