Javascript mouse location

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • hini
    New Member
    • Mar 2007
    • 23

    Javascript mouse location

    Hi all,

    I use IE, and I am trying to display a tooltip using javascript.
    the problem is that the tooltip is not apearing where I want it to be.
    I am getting the mouse location using clientX and clientY to display a div at the specified location, the problem happens when the page is scrolled down.
    any help would be appreciated.

    here is the code:


    [HTML]<html>
    <head>
    <title>Style Example</title>
    <script type="text/javascript">
    function showTip(oEvent) {
    var oDiv = document.getEle mentById("divTi p1");
    oDiv.style.visi bility = "visible";
    oDiv.style.left = oEvent.clientX + 5;
    oDiv.style.top = oEvent.clientY + 5;
    }
    function hideTip(oEvent) {
    var oDiv = document.getEle mentById("divTi p1");
    oDiv.style.visi bility = "hidden";
    }
    </script>
    </head>
    <body>
    <br/>
    <br/>
    <br/>
    <br/>
    <br/>
    <br/>
    <br/>
    <br/>
    <br/>
    <br/>
    <br/>
    <br/>
    <br/>
    <br/>
    <br/>
    <br/>
    <br/>
    <br/>
    <br/>
    <br/>
    <br/>
    <br/>
    <br/>
    <br/>
    <br/>
    <br/>
    <br/>
    <br/>
    <br/>
    <br/>
    <br/>

    <p>Move your mouse over the red square.</p>
    <div id="div1"
    style="backgrou nd-color: red; height: 50px; width: 50px"
    onmouseover="sh owTip(event)" onmouseout="hid eTip(event)"></div>
    <div id="divTip1"
    style="backgrou nd-color: yellow; position: absolute; visibility:
    hidden; padding: 5px">
    <span style="font-weight: bold">Custom Tooltip</span><br />
    More details can go here.
    </div>
    </body>
    </html>[/HTML]
  • mrhoo
    Contributor
    • Jun 2006
    • 428

    #2
    This code takes into account any window scroll values and returns a two integer (x,y) array for the cursor position.
    Code:
    function whereAt(e){
    	e= e || window.event;
    	var pX= (e.clientX) || 0;
    	var pY= (e.clientY) || 0;
    	if(window.pageXOffset != undefined){
    		pX+= window.pageXOffset;
    		pY+= window.pageYOffset;
    	}
    	else if(document.body.scrollTop != undefined){
    		var d= document.documentElement;
    		var b= document.body;
    		pX+= d.scrollLeft+b.scrollLeft;
    		pY+= d.scrollTop+ b.scrollTop;
    	}
    	return  [pX,pY];
    }

    Comment

    • hini
      New Member
      • Mar 2007
      • 23

      #3
      the solution worked,
      thx a lot mrhoo .

      Comment

      Working...