1

can you check in JS or JQuery in which part of the image was clicked?

For example we have this: Picture

Can you check if the user clicked on a specific pen? For example the red one?

Thanks

Hemran
  • 45
  • 5

3 Answers3

2

You have at least three options:

  1. Split the image into several images each with one pen, and then put them into a link that specifies the pen (e.g. <a href="#red"><img src="redpen.jpg" /></a>.

  2. You can use an HTML map with area tags.

  3. You can use the coordinates of your click event to decide which pen was clicked like described in this answer: https://stackoverflow.com/a/4249711/387573

Community
  • 1
  • 1
crackmigg
  • 5,571
  • 2
  • 30
  • 40
  • IMO 1 is the best - in case image will be resized, you don't need to wory about image map coords or click coords scaling – llamerr Mar 12 '16 at 14:39
1

use of image-mapping is better for this kind of requirement. map the required area and link to required url. know more about image-mapping http://www.w3schools.com/tags/tag_map.asp

ameenulla0007
  • 2,663
  • 1
  • 12
  • 15
0

If you don't want to use an image map you can also just detect the click's x & y position relative to the image and then from there, work out what you want to do.

This will not be very accessible but it will work.

You can work out the relative x & y position of the click like so. (Try clicking on the yellow pen)

var image = document.querySelector('img'); 

image.addEventListener('click', onClick, true);

function onClick(event){
  var imageBoundingRect = image.getBoundingClientRect();
    
    var x = event.pageX - imageBoundingRect.left;

    // We are not using the y co-ordinate but this is how you would get it.
    var y = event.pageY - imageBoundingRect.top;

 if (x >= 345 && x <= 380){
      alert('Clicked on the yellow pen.')
    }
}
<img src="http://www.wilde13-werbemittelkatalog.de/pictures/werbekugelschreiber.jpg"/>
Matt Vagni
  • 347
  • 1
  • 3
  • 9