Javascript get mouse position

Для ботов

Getting the Mouse Click Position

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.

Get Mouse Cursor Current Position in JavaScript jQuery Example

While this may be hard to believe, especially if you are familiar with how layout in HTML works, elements are positioned in some sort of sensible manner. Those manners are many and often confusing to discuss here, but there is some logic behind the position of everything you see. With great certainty, all elements end up at a particular location. The difficult thing to grasp is that, the location of an element is something you indirectly define by fiddling with parent elements, floats, paddings, margins, positions, and more. Very rarely will you set the position of an element using a precise X and Y value. In times that you do, those values are relative to whatever container you are in - a container whose own position may be set through mysterious ways. In this short tutorial, you will see the code for getting the exact position of an HTML element and learn why it works the way it does. This will be a good one, so let's get started! It returns an object containing an x property and a y property. You should also ensure you update the various position values when your browser is scrolled or resized. The updatePosition function helps you reset any values accordingly when those situations happen:. What you've seen here is just the basic usage. That is still an incomplete picture on how it works, so let's fix that in the next section. To see the code from the previous section at work, here is a live example. When you run the example, you will see a dialog that looks as follows:. This dialog tells you the position of an element you are looking for, and that element is the image of Nyan Cat with an id of imageLocation. The returned position is an x value of and a y value of If you use a 3rd party tool to measure the position from the top-left corner of your viewport to the top-left corner of the image, you will see that the position exactly matches what our code showed:. Let's talk a little bit more about this example. Like the example page's text mentions, the image is located inside a container that is absolutely positioned and has all kinds of CSS shenanigans applied to it. Despite that, our code was able to get the exact position. You can even try resizing your browser and scrolling the page around. The position will still be properly returned. Right now, you've seen the code. You've seen the example. All that is left is for you to understand why the code works. Before looking at each line in detail, let's talk a little bit about how layout for an element works in HTML. For the most part, an element's position is partly determined by its own CSS properties, but it is largely determined by its parent's CSS properties. The properties that I am referring to are primarily the paddingmarginand border. A great visualization of how those properties affect layout is by looking at the box model view for the element named container from our example:. Notice how the values for paddingmarginand border are represented in the diagram. At the far-left and top, you can see the left and top CSS properties represented because this element is absolutely positioned. To contrast the flamboyance of our containerlet's look at the image element. Our image lives inside this container, and it has no custom values defined for padding, margin, or border. If you look at the box model values for it, it looks pretty plain:. Despite nothing exciting happening with our image, because its parent is the container element you saw earlier, your image will inherit the layout and position settings of the parent. This drives home the point made earlier where the layout of an element is determined both by its own settings as well as the settings of its parent. What we have here is a relatively simple case. In something more complex, your element may have many MANY parents:. Each parent element might have its own special blend of paddings, margins, and borders that play a role in positioning a child element.

HTML5 Canvas Mouse Coordinates Tutorial

Are you ready to play with JavaScript? In this tutorial, I am going to show you how you can move an element to mouse position in JavaScript. I hope you are excited to see how I am going to move an element with the movement of the mouse cursor. If you run it on your browser, you will able to see a small red ball. But nothing will happen now. After we add our JavaScript code, you can see the small red ball on the screen moving with the movement of the mouse. Here we are actually going to move an element with mouse movement. This is to make it more attractive. In the above JavaScript code, we have used the clientX to get the position of our element from left and clientY to get the position of our element from the top. The clientX and ClientY property return the horizontal and vertical position of the mouse pointer when the mouse event triggered. Basically, in this tutorial, we have taken the x and y coordinate position of the mouse cursor and then apply it as the margin to our red ball or our element. Depending on the mouse position, we set the CSS margin to the red ball. Now the code is ready to test and you can run it on your browser. You can see that if you move your mouse on the page, then the red ball also move to the mouse position. With the movement of your mouse pointer, the red ball also moves in a nice way. Your email address will not be published. Please enable JavaScript to submit this form. Leave a Reply Cancel reply Your email address will not be published. This site uses cookies: Find out more. Okay, thanks.

Get an Element's Position Using 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! Serving you freshly baked content since !

Getting the current mouse position

Retrieve the position of the cursor caret within a textarea is easier than you think. Although you won't get a property named " cursorPosition " or " caretPosition ", you can deduct this value from the selectionStart property from the element which is basically the same. These values start and end provide always an integer value with the index of the selected text within a textarea or text input. In case that not any text is selected, those values start and end will be the same, which means that they're equivalent to the position of the cursor in the element. Every textarea and text input, should have available the selectionStart and selectionEnd properties which contains the character index of the start position of the selection and the character index of the end position of the selection respectively. The method will work independently of the kind of element input text or textarea on every modern browser. In order to provide support for old browsers, use the following method. The method is asynchronous, it expects as first parameter a DOM element wheter textarea or text input and it will return an object with 2 properties start and end equivalent to the values of selectionStart and selectionEnd. You can use it easily using the previous function remember to focus the input using the focus method to prevent any error :. The previous snippet was published in StackOverflow and the one who answered, created a repository with MIT license. Interested in programming since he was 14 years old, Carlos is the founder and author of most of the articles at Our Code World. Proud Self-taught programmer.

Convert Mouse Clicks to Geo Coordinates with HERE and JavaScript

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>