Sunday, January 2, 2011

How To Capture The Exact Pixel Where Mouse Is Present

Posted by Shiva Gouraram | Sunday, January 2, 2011 | Category: |


Hello friends,today i`m going to explain an interesting topic on how to capture the exact pixel position where mouse is exactly present at a particular time,at this point you all will  get a small doubt on what is the use by knowing the mouse position,yeah i will explain why we need this,
Consider a situation where you need to place an image or link or something else at a particular pixel position but you does not know the exact value,thus we make many attempts by changing margin each time until we get the exact position where you need that,thus results in waste of time.
So by this tutorial you will easily find the exact pixel position and thus you can easily put on margin.
So let us start,we use a piece of javascript and two line html.
lets begin the entire code for doing this is below.

<html>

<head>

<script>

function init()

{

 if (document.layers)

    document.captureEvents(Event.MOUSEMOVE);

 document.onmousemove=change;

}



function change(e)

{

 if(arguments.length==0) e=event;



    document.getElementById('xx').value=(document.layers)?e.pageX:e.clientX;

    document.getElementById('yy').value=(document.layers)?e.pageY:e.clientY;

}   



</script>

</head>



<body onload='init()'>

X:<input type=text id=xx value=0 size=4/><br>

Y:<input type=text id=yy value=0 size=4/><br>

</body>
</html>
Copy the code and save as html file see the result,now i explain a bit of it,first function init() captures mouse event on each change of mouse position and second function use to find the mouse x position and y position and sends to html,
thus by finding mouse x and y position we can find out where mouse is exactly present!
Thus we can easily implement it in margin for any image or something what we need!

Example if you move your mouse to a certain position and you got a position you liked consider "X" value as "margin-left" and consider "y" value as "margin-top" that's it!you will see your object where you want!

Wanna see an example please click HERE
Hope you liked this post!
Reply to this post if you have any doubt!
Share/Bookmark

Currently have 0 comments:


Leave a Reply

Subscribe