Javascript get mouse position

How to find mouse position relative to an element using jQuery

As I was working on the new recolorable Garland Drupal themeI noticed that suddenly my Farbtastic color picker wasn't working right anymore in IE. A lot of headscratching later, I found the cause and discovered a useful trick for dealing with mouse coordinates in JavaScript. Essentially, when you click on Farbtastic, the mouse position is compared to the position of the color picker, so we can determine which color you clicked. Sounds simple? Well, no. Unfortunately, even this does not work well. Various browsers have various quirks, but no surprise IE wins the contest hands down. When you try to resolve absolute positions in any sort of advanced CSS-based layout, the return coordinates are often completely wrong. This is exactly what was happening in the new completely tableless Garland theme. After trying various ways to correct the absolute values, I decided I didn't want to waste hours of my life cleaning up after somebody elses mess. And of course, hardcoding in the correction is mostly useless in a dynamic CMS like Drupal. I did come up with an alternative which works well enough, and is perfectly suited for making self-contained HTML widgets: that's the most common use case after all. You see, aside from the absolute mouse position event. Now, if we try to resolve these coordinates back to the root of the page, we end up with the same problem. The trick is to realize that we often don't need completely absolute coordinates: all we need is coordinates relative to a common reference frame. So, we need to find the closest, common offsetParent for the clicked element and the reference element, and then compare the coordinates in that frame. The snippet below achieves this. As most of the bad offsetParent numbers are located very high up in the page hierarchy, they are practically never used with this approach. Typically you only go up one or two offsetParents and there is no error. Firefox or tend to screw it up e. So using that as a fallback, we end up with the following function, which works in every browser I've tried:. Obviously if the elements you apply it to have an exotic positioning, it'll still go sour, but the above code at least improves the situation massively in Internet Explorer. Here's a little example. October 27, This article contains graphics made with WebGL, which your browser does not seem to support. Try Google Chrome or Mozilla Firefox.

Getting the current mouse position


Hi all, 1. Is there any way to Set the mouse position in Javascript? There are some methods to get it that I know 2. Is there any method to hide the mouse pointer through javascript. If you want to capture the mouse position as it moves around the screen, then include this function in your web page. You will want to put this code into the JS Header section of your form. We put the code into a JavaScript page a page design element named with a. You will have global variables of xMousePos and yMousePos that will give you the proper position of the mouse, no matter how much the user has scrolled. Something can appear at the mouse's position using those variables. So, the mouseover event of a link could have something appear below the user's current position on the page. You do not need to make any additional calls during the mouseover event because xMousePos and yMousePos are constantly being captured. The variables xMousePosMax and yMousePosMax will have the height and width of the page in relation to the position of the mouse. So if you want to have something appear that is 60 pixels tall, you can compare xMousePos to xMousePosMax to see if there is 60 pixels of room for the item to fit below. If you want to see this really work, then at the very bottom of the "captureMousePosition" function, put in a call to put the current values in the status bar. So, the line would read something like: window. In fact, that is what this page is doing when you are not over another link - as you move around the page, the values change in the status bar and you can see what affect scrolling has on the values especially the "yMousePosMax" value. I didn't write this - I just copied it because it might come in useful one day. Hope I haven't broken any rules This could be a serious lapse of security, not to mention extremely annoying. As mentioned above, however, you can track where the cursor currently is or even what element it is currently pointing at within the browser canvas. I would really wonder the purpose of this, however. Hi Thanks for your kind information. Since my project has such a reqiurement Such as set mouse position, so that by exporting some frames to DHTML and should simulate some actual mouse movements which looks like animation. Anyway thanks again because I am quite new to this scripting field.

HTML5 Canvas Mouse Coordinates Tutorial


Sign in to post your reply or Sign up for a free account. By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings. Join Now login. Ask Question. My appologies if this sounds stupid, I wish I had a "Comprehensive" reference for javascript. I'm not sure one exists. I would like to develop a web application that has a learning mode, in which the user is walked through using the site. I would like to Present information, then reposition the mouse by gradually moving it to a new position, that of a link for example, and then simulate a button click, or tool selection. I haven't had much luck finding any info on the subject, a definative "Can't be done" would suffice. But no information usually indicates that I haven't looked hard enough. Thanks, Dan. Feb 4 ' Post Reply. Share this Question. Feb 5 ' Is there a way to hide the mouse? Then I could use a mouse shaped bitmap instead. I notice that sometimes it dis appears. LIke maybe select a mouse cursor that is completely see through? I've never tried, but you could try adapting something like this. Feb 6 ' Apr 2 ' Iframes and Mouse Position mouse click location can't set mouse cursor Mouse event onclick trying to use mouse effect script in multiple frames? Question stats viewed: replies: 4 date asked: Feb 4 '08 Follow this discussion. Follow us to get the Latest Bytes Updates. Is it possible to set the mouse position in javascript? P: Thanks, Dan - Feb 4 '08 Post Reply. Feb 5 '08 reply. Feb 6 '08 reply. Cancel Changes.

Get current mouse cursor position with Javascript


Help to translate the content of this tutorial to your language! The mouseover event occurs when a mouse pointer comes over an element, and mouseout — when it leaves. These events are special, because they have property relatedTarget. This property complements target. When a mouse leaves one element for another, one of them becomes targetand the other one — relatedTarget. In the example below each face and its features are separate elements. When you move the mouse, you can see mouse events in the text area. Or that it left the window. We should keep that possibility in mind when using event. If we access event. The mousemove event triggers when the mouse moves. The browser checks the mouse position from time to time. And if it notices changes then triggers the events. That means that if the visitor is moving the mouse very fast then some DOM-elements may be skipped:. If you move the mouse fast over them, then maybe only the child div triggers events, or maybe the parent one, or maybe there will be no events at all. Also move the pointer into the child divand then move it out quickly down through the parent one. If the movement is fast enough, then the parent element is ignored. The mouse will cross the parent element without noticing it. An important feature of mouseout — it triggers, when the pointer moves from an element to its descendant, e. According to the browser logic, the mouse cursor may be only over a single element at any time — the most nested one and top by z-index. The mouseover event on a descendant bubbles up. So, if parent has mouseover handler, it triggers:. If you move the mouse from parent to childyou see two events on parent :. As shown, when the pointer moves from parent element to childtwo handlers trigger on the parent element: mouseout and mouseover :. The pointer is still over the parent, it just moved deeper into the child element. If there are some actions upon leaving the parent element, e. To avoid it, we can check relatedTarget in the handler and, if the mouse is still inside the element, then ignore such event. When the pointer enters an element — mouseenter triggers. As you can see, the only generated events are the ones related to moving the pointer in and out of the top element. Nothing happens when the pointer goes to the child and back. Transitions between descendants are ignored. But they do not bubble. Here they are in action. As the mouse travels across the elements of this table, the current one is highlighted:. Try to move the cursor in and out of table cells and inside them. We covered events mouseovermouseoutmousemovemouseenter and mouseleave. The browser assumes that the mouse can be only over one element at one time — the deepest one. Also they do not bubble. Write JavaScript that shows a tooltip over an element with the attribute data-tooltip.

Move an Element to Mouse Position in JavaScript

For all sorts of interactive doo-dads you will be creating, chances are you will be making heavy use of the mouse or another pointing device like a stylus or finger. Something you may find yourself needing to do is figuring out the exact position of the click. Let's look at an example where knowing the exact click position is important:. In this tutorial, I will explain the magic behind figuring out the exact pixel coordinates of where a click occurred. While the words "mouse" and "click" will appear often, just know that everything I show here works on a touch device where a stylus or your finger is the pointing thing! A great way to learn is by understanding why something doesn't work the way it should. In that thread, let's start by looking at a seemingly fine approach that seems like it should give us the exact position of the click. What we want to do is figure out the exact click position when you click anywhere inside the yellow container:. First, we have the event listener setup to listen for a click event:. If any of this event handling jibberish is confusing or unfamiliar, you should first check out my JavaScript Events tutorial before proceeding further. It is a quick read, and it will help the rest of this tutorial make a lot more sense! Notice what this event handler contains. It contains two variables whose values are the contents of our event object's clientX and clientY properties. These properties return the X and Y position of the click. That is their documented behavior, and that is what they actually do. Sounds exactly like what we are looking for, doesn't it? The problem is this. The X and Y position returned by clientX and clientY is relative to the element you clicked on:. It is neither global nor relative to the browser, so the value you get is only partially accurate for what you are trying to do. You want the X and Y position based on the top-left aka the starting position corner of your document. It is this value that gives you the exact position of your click. It is this value you will need when using the position for doing clever things like moving an element to the point of the click. The solution is pretty simple. What we need is to do some more calculations to make our partially accurate answer fully correct! The full solution involves combining the values returned from clientX and clientY that you saw earlier with the positions of every element in the DOM going up to your window object. That sounds complicated, but it really isn't. To get the position of all the elements between what you clicked on and the document, you have the getPosition function. This function provides you with the additional pieces of information needed to make your existing calculations involving clientX and clientY complete. All you need to do is pass in the element you are starting your measurement from. Inside an event handler, that element can be accessed by the currentTarget property. Now, I am not going to explain in this tutorial how getPosition works or the logic behind why the code does what it does. The reason is besides me being horrifically lazyyou can see my full explanation in the Get an Element's Position Using JavaScript tutorial instead. The getPosition function I used here was stolen from that tutorial, and it is a good read if you want to understand more about how positions in HTML can be calculated. Well, that is all there is to this little tutorial. Getting the click position of something seems easy, but as you saw, it involves a lot of interesting factors that you need to take into account. Got a question or just want to chat? Comment below or drop by our forums they are actually the same thing! Get cool tips, tricks, selfiesand more View past issues for an idea of what you've been missing out on all this time!

getBoundingClientRect() in Javascript DOM



Comments on “Javascript get mouse position

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>