jQuery Add click event if cursor between coordinates

1.3k views Asked by At

If I have to following HTML which is a image of a map. The map is divided into colour areas. My goal is if the cursor is over an area of the image, to swap the image.

<div id="map" class="mouse-click"><img class="image-swap" src="images/map.png" /></div>

I can find the X Y Coords with

$('#map').mousemove(function(e){
    var x = e.clientX - this.offsetLeft;
    var y = e.clientY - this.offsetTop;
    $('#map-xy').html("X: " + x + " Y: " + y); 
});

How do I add a click event to swap the img if the cursor is between a set of coordinates.

Any help is appreciated.

1

There are 1 answers

7
Ansel Santosa On BEST ANSWER
$('#map').on('click', function(e){
    var x = e.clientX - this.offsetLeft,
        y = e.clientY - this.offsetTop;
    if (x > xMin && x < xMax && y > yMin && y < yMax) {
        // click was in target zone, swap img
    }
});

Where xMin, xMin, yMax, and yMin describe the boundaries of the target area.