Get position of map area(html)?

15,799

Solution 1

Edit for updated question: Since you're using <area> it's a different story, and fetching from the coords attribute is much easier, like this:

var position = $(this).attr('coords').split(',');
x = +position[0] - 50;
y = +position[1] - 170;

The offsets are just to account for the hard-coded width/height of the tooltip itself. In addition to the above, you want to use top and left rather than margin-top and margin-left. Also to account for the #content <div>'s position in the page, give it a relative position for the tooltip to sit in, like this:

#content { position: relative; }

Then...instead of .after(), use .append() so it gets added inside that parent.

You can test the result here.


For original question:
The object .position() returns has top and left properties...but you want .offset() here anyway (it's relative to the document, where .position() is relative to the offset parent), so it should look like this:

var position = $(this).offset(),
    x = position.left,
    y = position.top; //not right!

Or this:

var position = $(this).offset();
var x = position.left;
var y = position.top;

...but without a single var comma-separated statement, or a var on each line, you're also creating (or trying to) global variables, which will blow up in IE.

Solution 2

The problem lies in the fact that you are accessing the top/left of an area element.

The area element is not positioned where its coords say. This is handled behind the scenes by the dom/browser.

So you need to find the image that the area relates to and grab its offset.

var imgId = $(this).closest('map').attr('name');
var imgPos = $('#' + imgId).offset();

Then, you grab the coords attribute of the area and split it to get left/top/width and use those to pinpoint the location inside the image.

var coords = $(this).attr('coords').split(',');
var box = {
            left: parseInt(coords[0],10),
            top: parseInt(coords[1],10),
            width:  parseInt(coords[2],10)-parseInt(coords[0],10),
            height:  parseInt(coords[3],10)-parseInt(coords[1],10)
            };

Take into consideration the width/height of the info box that appears (and since you animate it, take that into consideration as well) and you get to

x = imgPos.left + box.left + box.width/2 - 65; // 65 is the info width/2
y = imgPos.top + box.top -20 -160 -1; // 20 is the animation, 160 is the info height, 1 is a safe distance from the top

demo: http://www.jsfiddle.net/XBjwN/

Share:
15,799
switz
Author by

switz

Updated on June 08, 2022

Comments

  • switz
    switz about 2 years

    Is this possible? I'm trying to find the x and y coordinates of the element in relation to the browser.

    var position = $(this).position();
        x = position.left;
        y = position.right;
    

    Doesn't work.

    Is there any way to do this?

    http://adamsaewitz.com/housing/
    highlight the blue room 070