Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Getting the position of an element

Status
Not open for further replies.

stinkybee

Programmer
May 15, 2001
218
GB
I am trying to write a script that displays a div of information in a position relative to an element on my page. For example, when you hover over a link I want a div to appear next to the link. Therefore I need to find the position of the link on the page so I can move the div element to the right position.

I have tried a few scripts but none of them work for both IE and Firefox. The top value is always ok but the left value leaves my div in different places depending on browser and size of the browser window. Here is an example script that I have been using.

Code:
function getPos(obj) {
var pos = {x: obj.offsetLeft||0, y: obj.offsetTop||0};
while(obj = obj.offsetParent) {
pos.x += obj.offsetLeft||0;
pos.y += obj.offsetTop||0;
}
return pos;
}

This supposedly gives me the left and top of my link element but when I try and display my div element at these coordinates it displays in a different place depending on browser type and window size. I want my div element to show in the same place regardless of these factors.

If anyone could give me a script that works or inform me how I could make the above script work that would be great.
 
Thanks for the reply. Do you know how I would utilise a function that detects the mouse position. This is the function I found from your link

Code:
function doSomething(e) {
	var posx = 0;
	var posy = 0;
	if (!e) var e = window.event;
	if (e.pageX || e.pageY) 	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		posx = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}
	// posx and posy contain the mouse position relative to the document
	// Do something with this information
}

In my code I have an onmouseover event in my link that calls a function that fills my div with content and displays it. I am not sure how I would call the above function from my function in order to get the mouse position values.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top