I am having a background image in which I am in the need to add a click event to a particular portion/block.
Portion/Block where click event needs to handled:
Code tried:
const div = document.querySelector('.container');
div.addEventListener('click', () => {
alert('The background image was clicked!');
});
div {
background-image: url("https://phpout.com/wp-content/uploads/2023/04/AfygH.png");
width: 800px;
height: 400px;
background-repeat: no-repeat;
}
<div class="container"></div>
This code gives alert wherever we click in the background image and I agree like that only I have made my code.
Requirement:
But requirement is that how can I show the alert on click of particular portion/block in an image as like highlighted in the above image in green color?
2
Answers
You could try putting another invisible div on top of the background, with css:
Or whatever size/position you want. And attach the click event to the invisible div. If click event still doesn’t work, make sure the invisible div is on top of the background div (z-index).
you are receiving alert where ever you click, because that’s the element you attached your event listener to.
the best way to achieve what you want is to create a transparent div and place it on top of the background image with whatever size or position you want.
then, you can attach your event listener to this transparent div.