SAK
SAK

Reputation: 3900

javascript div positioning

I am using this script to display an image as popup on mouseover. The difficulty I am facing is that it is not positioning well in different monitor. It must be something to do with resolution.

function LargeImage(obj, e)
{
  var imgbtn=document.getElementById('<%=imgbtn1.ClientID%>');  
  imgbtn.src=obj;//source of the image
  document.getElementById('imgbox').style.visibility="visible";
  document.getElementById('imgbox').style.position="absolute";
  document.getElementById('imgbox').style.left=e.clientX-150 + "px";
  document.getElementById('imgbox').style.top=225 +"px"; 
} 

<div id="imgbox"><asp:imagebutton id="imgbtn1" runat="server" OnClick="ImageButton4_Click"/></div>

Thank you.

Upvotes: 1

Views: 10788

Answers (2)

lincolnk
lincolnk

Reputation: 11238

you can do this

document.getElementById('imgbox').style.position="fixed";
document.getElementById('imgbox').style.left=e.clientX + "px";
document.getElementById('imgbox').style.top= e.clientY + "px"; 

which will show the picture at the mouse location in the window (popup stays put if the user scrolls).

otherwise you need to compensate for document scrolling, something like

edit: fix the scroll value (for firefox)

document.getElementById('imgbox').style.position="absolute";
document.getElementById('imgbox').style.left=String(e.clientX+document.documentElement.scrollLeft)+"px";
document.getElementById('imgbox').style.top=String(e.clientY+document.documentElement.scrollTop)+"px"; 

you can look here to find a demo of determining which property to read for scrolling offsets by browser http://www.howtocreate.co.uk/tutorials/javascript/browserwindow

Upvotes: 4

Damovisa
Damovisa

Reputation: 19423

You look like you're modifying the style of the imgbox div so that the left position is 150px left of the cursor, but the top position is just 225px from the top of its container (probably).

Should the top style be relative to the cursor as well?

Also, we can't see from your posted code when or how your function is being called. We also have no context for the imgbox element. More information would be useful.

Upvotes: 0

Related Questions