Positioning draggable images with Javascript position() - javascript

I have a website with a draggable image inside a div, the script code looks like this:
var offset = 0,
xPos = 0,
yPos = 0;
$(document).ready(function(){
$(".item").draggable({
containment: '#house_wall1',
drag: function(){
offset = $(this).position();
xPos = offset.left;
yPos = offset.top;
$('#posX').text('x: ' + xPos);
$('#posY').text('y: ' + yPos);
},
// Find original position of dragged image.
start: function(event, ui) {
// Show start dragged position of image.
var Startpos = $(this).position();
$("div#start").text("START: \nLeft: "+ Startpos.left + "\nTop: " + Startpos.top);
},
// Find position where image is dropped.
stop: function(event, ui) {
// Show dropped position.
var Stoppos = $(this).position();
$("div#stop").text("STOP: \nLeft: "+ Stoppos.left + "\nTop: " + Stoppos.top);
}
});
});
My problem is that the x and y values are specified from the edge of the screen and not the div that they are supposed to. So if you have a screen with a lower resolution or if you make the browser window smaller then the x and y values will differ from a screen with a lower resolution.
I posted a problem similiar to this earlier and thought it was fixed, but unfortunatly it wasn't. I heard that using position() instead of offset() should do the job, but this still fix nothing. Maybe it's because the position() is equal to offset() in this case?
Thanks in advance.

if you want a div as coordinates origin for left and top. you have to set the position style property. div position="relative" or div position absolute

sorry, i forgot to mention that also the offset Properties are relative to the next parent which has positon: relative or absolute, if no parent has set the position property, the origin for IE is the client origin, what mozilla does is suspect for me, i hope they changed that soon to IE standard. you can see the difference by putting a border to the document.body and setting a div element to the document body and call alert (divid.offsetLeft); IE and mozilla will throw different values. Mozilla shows a value which only includes the body margin but not the border, and if you do a document.body.offset in mozilla it show a minus value????..... which is 0 in IE
exception are table inner Elements like td and tr , for them the table is the offsetParent

Related

How to get position of a square div jQuery/JavaScript

setInterval(function() {
var divPosition = $('div').position();
console.log('X: ' + divPosition.left + ", Y: " + divPosition.top");
}, 500);
So I can get the x and y position of this div. left/top but it's a square div on the page. I'm also tracking a section tag that flies around the page, I want to basically do if (_thesectiontag_.left == _thesquarediv_.left || _thesectiontag_.top == _thesquarediv_.top) ... do something so if the section tag is within the div coordinates on the page do something.
But I need to get the full dimensions of the square to be able to do that. I'm a bit lost on where to start and how to go about it.
Can anyone offer some help? Thank you!
Use this two code :
For the Width and Height includes padding :
var Height = document.getElementById('square').clientHeight;
var Width = document.getElementById('square').clientWidth;
For the Width and Height includes padding, scrollBar and borders :
var Height = document.getElementById('square').offsetHeight;
var Width = document.getElementById('square').offsetWidth;
$('div').height($('div').width());

How to dynamically change the position of an absolute tooltip base on the target element

I am trying to make a tooltip which basically shows a table (in my example below I used a large amount of text).
However I've wanted to change the position of the tooltip when you hover on the target element that is nearly at the corner of the screen.
Here is the Fiddle
$("strong").on("mouseover", function(){
var $this = $(this),
strongText = $this.text();
$tooltipContainer.show();
$tooltipContainer.append('<span>'+ strongText + '</span>');
}).on("mousemove", function(mousePos){...
You can change your mousemove code a little to update top position if overlap is there like below. Check demo - Fiddle
on("mousemove", function(mousePos){
var overlap = mousePos.pageY + posSrollY + $tooltipContainer.height() - $(window).height() - $(window).scrollTop();
$tooltipContainer.css({
left: mousePos.pageX,
top: mousePos.pageY + posSrollY - ( overlap > 0 && overlap )
});
})

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>

Get position of map area(html)?

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"))
}, )
});

Categories

Resources