skip to Main Content

I am having a background image in which I am in the need to add a click event to a particular portion/block.

BG Image:
enter image description here

Portion/Block where click event needs to handled:

enter image description here

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


  1. You could try putting another invisible div on top of the background, with css:

    {
        opacity: 0;
        position: absolute;
        top: 50px;
        left: 50px;
        width: 100px;
        height: 100px;
    }
    

    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).

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search