javascriptjquerypixeljquery-eventsmouse-position

Detecting position of mouse click within an image on varied screen sizes - Jquery/JavaScript


I've got an initial div called "container" which is a height:100% width:100% image of an Oklahoma map. The idea is that when the user clicks a certain section of the map (for this example, the panhandle), the div is toggled to a div which is the panhandle image. I determine where the user clicks by knowing the pixel location of the mouse when it clicks.

The problem is, pixel values are different for different size screens. Below is the code which works for my own sized window, but when I run the code for the actual program, the window is smaller and thus the area described within the if statement is not around the panhandle.

$(document).ready(function()
{
    $("#container").click(function(e)
    {
        var x = event.pageX;
        var y = event.pageY;

        if(x >= 45 && x <= 550 && y >= 245 && y <= 330) 
        {
            //alert('You clicked the panhandle!');
            $("#region1").toggle();
            $("#container").toggle();
        }
}); 
});

I'm thinking I need to change how I handle the situation within the if statement. How would you approach this?


Solution

  • You need to scale every value before you compare it. Multiply every x by your canonical width and divide by the actual width and do the same with y and height.