Get position of map area(html)? - javascript

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

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/

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.

$(document).ready(function () {
$('map').imageMapResize();
$('area').hover(function () {
$('.imgpopover').css({ "display": "block", "top": $(this).attr("coords").split(',')[1]+"px", "left": $(this).attr("coords").split(',')[0]+"px" })
$('.imgpopover label').text($(this).attr("title"))
}, )
});

Related

How to find css unit for this number

I have a input type text
<input type="text">
Basically I am using javascript ClientRect to get caret details. ClientRect looks like this
[object ClientRect]
{
[functions]: ,
__proto__: { },
bottom: 540.7999877929687,
constructor: { },
height: 24,
left: 1034.5399169921875,
right: 1034.5399169921875,
top: 516.7999877929687,
width: 0
}
This is generated on everytext input.
left: 1034.5399169921875,
left: 1065.5399169921875,
left: 1078.5399169921875,
I want to convert this number to CSS units like px/%/rem/vh. So that I can put dynamic css. How to do it?
Try accessing the left position of your input and subtract the left position of your caret. This should give you an approximate width of the text in the input, if that's what you are looking for. You'll need to add an id or create a selector for your text input.
var inputElementRect = document.getElementById('YOURINPUTID').getBoundingClientRect()
var width = inputElementRect.left - caretRect.left
Those values are px by default .. so just add suffix as px to that value and use it.
<input type="text">
to get that value
let text = document.querySelector('input');
let values = text.getBoundingClientRect();
let top_value = values.top + 'px';
let bottom_value = values.bottom + 'px';
let width_value = values.width + 'px';
let height_value = values.height + 'px';
console.log('top: '+ top_value);
console.log('bottom: '+ bottom_value);
console.log('width: '+ width_value);
console.log('height: '+ height_value);
here properties other than width and height are relative to the view port ( top, bottom, left, right ) ,
so if scroll this values will changes ..
to get the perfect values even if scroll add this values with window.scrollX , window.scrollY or can use window.pageXOffset , window.pageYOffset
So if I understand the question correctly, you have position values for the cursor inside of the input and you want to convert it into different types of CSS units, presumably so you can do something to the input or related things
The first thing to understand is that ClientRect positions are relative to the viewport. So as vhutchinson pointed out, if you want the width of text you need to compare to the input's "left" value as defined by getBoundingClientRects. That's a good start, but if you're not just influencing left but also care about top, you need to account for scrolling. If your window/page is the only scrolling container, you should be able to do this simply by adding window.scrollY to top, and window.scrollX to left to understand your offset relative to the window.
All of these units are pixels by default... if you want to convert to rem it's pretty straightforward, 1 rem = the font-size of your root element, so to convert to rem you can do something like
var remBase = parseInt(window.getComputedStyle(document.body).getPropertyValue('font-size'), 10);
var remValue = (myComputedPixelValue / remBase) + "rem";
Doing VW is similar using the answer in Get the browser viewport dimensions with JavaScript for cross-browser window dimensions, you'd end up with something that looks like
var viewportWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
var vwValue = (myComputedPixelValue / viewportWidth) + "vw";
Percentages are trickier, because you'd need to compute it based on the parent of the element you're applying the css value to, but the general idea follows the same principle.

How to get the left and top position of a child element of its parent

I have a parent-child structure of div elements (parent is the div called dartboard, a child div called rotatingDiv and that then has a child called crosshair).
dartboard
> roatingDiv
> crosshair
The dartboard container holds a rotating container (rotaingDiv), which then holds a child element (crosshair). I would like to find the x and y positions in relation to the dartboard container. Here is what I have at present:
$('#dartboard').append( $('#rotatingDiv').append( $('#crosshair') ) );
X = $('#crosshair').position().left.toFixed(1)
Y = $('#crosshair').position().top.toFixed(1)
console.log("x is "+X+", y is "+Y);
This process runs within a per-second timer, upon inspection of the x and y values, I've noticed that i'm only receiving this information in relation of the crosshair element being inside the rotatingDiv instead of being at the dartboard level (parent of parent). Does anyone know how I can do this?
Try this:
var parentLeft = $('#parent').offset().left,
parentTop = $('#parent').offset().top
childLeft = $('#child').offset().left,
childTop = $('#child').offset().top;
// Positions respective to parent
var top = parentTop - childTop,
left = parentLeft - childLeft;
You can also use position.
This should work:
var pos1 = $("#crosshair").position();
var pos2 = $("#crosshair").parent().position(); // or $('#rotatingDiv').position();
var x = (pos1.left + pos2.left ).toFixed(1);
var y = (pos1.top + pos2.top ).toFixed(1);
Be careful:
Note: jQuery does not support getting the position coordinates of
hidden elements or accounting for borders, margins, or padding set on
the body element.
You can check the API here.

Javascript get absolute position of a div

I have a div (oCell) created at runtime using javascript.
I then want to position another independant div (random-div) relative to this div. For reasons within the program random-div has to be positioned absolutely and oCell relatively. The oCell div is positioned relative as it is within a table.
My problem is I need to find the absolute position of the oCell div, rather than the relative position.
So far I have:
var oCell = document.createElement("td");
var height = oCell.getBoundingClientRect().top;
var right = oCell.getBoundingClientRect().right;
oCell.oBoxPositionTop = height;
oCell.oBoxPositionSide = right;
But from what I can understand, this is returning the relative height of oCell div, which is in turn not positioning random-div in the correct place.
The getBoundingClientRect gives coordinates in viewport coordinates (or coordinates relative to the visible content shown in your browser window). With absolute positioning, you need document coordinates. To convert viewport coordinates to document coordinates, add the scroll offsets of the page to the left and top values returned by getBoundingClientRect:
//technique used in JavaScript: Definitive Guide
var scrollOffsets = (function () {
var w = window;
// This works for all browsers except IE versions 8 and before
if (w.pageXOffset != null) return {x: w.pageXOffset, y:w.pageYOffset};
// For IE (or any browser) in Standards mode
var d = w.document;
if (document.compatMode == "CSS1Compat")
return {x:d.documentElement.scrollLeft, y:d.documentElement.scrollTop};
// For browsers in Quirks mode
return { x: d.body.scrollLeft, y: d.body.scrollTop };
}());
//Your code:
var oCell = document.createElement("td");
//changed from height to top and gets document coordinates of position
var top = oCell.getBoundingClientRect().top + scrollOffsets.y;
//changed from right to left
var left = oCell.getBoundingClientRect().left + scrollOffsets.x;
oCell.oBoxPositionTop = top;
oCell.oBoxPositionSide = left;

Getting every offsetParent or the total offSetTop and total offSetLeft

I want to get the total offSetTop and the total offSetLeft of a child element which have many level of parent element and may be adding up.
Is that any shorthand way, besides of adding one by one in manual ways?
To provide an answer without jQuery:
var a = Element, b = 0, c = 0;
while (a) {
b += a.offsetLeft;
c += a.offsetTop;
a = a.offsetParent;
}
Where Element is your Element node for which you need an offsetLeft and offsetTop.
using jQuery: $( node ).offset() then .top and .left
https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
If you need the bounding rectangle relative to the top-left corner of the document, just add the current scrolling position to the top and left properties (these can be obtained using window.scrollX and window.scrollY) to get a bounding rectangle which is independent from the current scrolling position.
let { left, top } = domNode.getBoundingClientRect();
left += window.scrollX;
top += window.scrollY;

how do i get the x and y position directly under the left bottom side of the input rectangle?

I'm thinking of implementing a custom auto-complete feature so basically my idea now is that i will make an abs positioned div and give it the position here:
(image) http://i.stack.imgur.com/3c5BH.gif
So my question is with a variable referencing the textbox, how do i get the x and y position directly under the left bottom side of the input rectangle?
My script must work in latest versions of IE / FF / Safari / Opera / Chrome
I know i can use a library to do it, but no i'm interested in learning how do they do it (or maybe better ways)?
This question is a lot more complicated than it seems and involves getting the position of the element relative to the document. The code to do so can be pulled from the jquery source (http://code.jquery.com/jquery-1.6.1.js -- search for "jQuery.fn.offset")
in jQuery:
var node = $('#textbox'),
pos = box.offset(); // the complicated piece I'm using jQuery for
node.top += node.height(); // node.offsetHeight without jQuery
node.left += node.width(); // node.offsetWidth without jQuery
The answer can be extremely simplified if you don't care about FF2 or Safari3:
var box = document.getElementById('yourTextBox').getBoundingClientRect(),
left = box.left,
bottom = box.bottom;
x = x offset
y = y offset - ( textbox height +
padding-top + padding-bottom )
Good comments! For my scenario, there is always an offset parent (which is why I use position - http://api.jquery.com/position/). In hopes that it might help someone else wanting a quick fix, here's the code:
// I have a parent item (item) and a div (detail)
// that pops up at the bottom left corner of the parent:
var jItem = $(item);
var pos = jItem.position();
var marginTop = parseInt(jItem.css('margin-top'));
if (isNaN(marginTop)) {
marginTop = 0;
}
$(detail).css("top", pos.top + jItem.outerHeight() + marginTop)
.css("left", pos.left);
$(detail).show();
Just give the box a defined width and height. Then, get its top and left property and add it with the width and height. Simple. I am gonna give you Pseodocode.
<STYLE>
object{width: 100px; height: 20px;}
</STYLE>
<SCRIPT>
x = object.left;
y = object.top;
x = x + object.width;
y = y + object.height;
</SCRIPT>

Categories

Resources