Detecting mouse click position in image with different screen sizes - jQuery / JavaScript

I have an initial div called a “container”, which is an height:100% width:100%image of a map of Oklahoma. The idea is that when the user clicks on a specific part of the map (for this example, the pan knob), the div switches to the div, which is the pan image. I determine where the user clicks, knowing the location of the mouse pixel on click.

The problem is that the pixel values ​​for different screens are different. Below is the code that works for my own window size, but when I run the code for a real program, the window is smaller and therefore the area described in the statement ifis not around the pan handle.

$(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 think I need to change how I handle the situation in the instructions if. How do you approach this?

+3
source share
2 answers

You need to scale each value before comparing it. Multiply each x by its canonical width and divide by the actual width and do the same with y and height.

+3
source

, - , iPad Android, dpi ..

- % /. , (0,23,0,76) (0,12,0,08) ..

%, .

0

All Articles