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.
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.
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 or Set Cursor Position in a Textarea: How to get cursor position and selected text position in textarea. Also set text selection into textarea from start and end index. What do you think of this article?
Get or Set Cursor Position in a Textarea If you have ideas about this article, or an opinion on how we can make it better, then let us know by emailing… help codescratcher. And the textbox have two-way binding. Can anyone suggest me solution for this.
Your email address will not be published. Leave this field empty.How to get the Absolute Position of the Mouse on the Screen
React Component Lifecycle Methods. Different ways and explanations to start creating React applications. Add less file into visual studio. A basic understanding of React terminologies. Generate and Print Barcode in VB. Windows Forms. Get Computer Hardware Information using C.
This will help you improve your skills in programming, better understand concepts from articles. Code Scratcher builds your confidence and ability to quickly learn new concepts and technologies like ASP.
Read More. NET 6 Feb, NET 12 Jan, This code is amazing. Thx very much, i hav export to csv prolem with ';' Hey, This code is useful but it didn't work on mobileRetrieve 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.
Subscribe to RSS
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.
Getting the current mouse position
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.The position property specifies the type of positioning method used for an element static, relative, fixed, absolute or sticky. The position property specifies the type of positioning method used for an element.
Elements are then positioned using the top, bottom, left, and right properties. However, these properties will not work unless the position property is set first. They also work differently depending on the position value. An element with position: static; is not positioned in any special way; it is always positioned according to the normal flow of the page:.
An element with position: relative; is positioned relative to its normal position. Setting the top, right, bottom, and left properties of a relatively-positioned element will cause it to be adjusted away from its normal position.
Other content will not be adjusted to fit into any gap left by the element. An element with position: fixed; is positioned relative to the viewport, which means it always stays in the same place even if the page is scrolled. The top, right, bottom, and left properties are used to position the element. An element with position: absolute; is positioned relative to the nearest positioned ancestor instead of positioned relative to the viewport, like fixed.
However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.
Note: A "positioned" element is one whose position is anything except static. An element with position: sticky; is positioned based on the user's scroll position.
A sticky element toggles between relative and fixeddepending on the scroll position. It is positioned relative until a given offset position is met in the viewport - then it "sticks" in place like position:fixed. Note: Internet Explorer, Edge 15 and earlier versions do not support sticky positioning.
Safari requires a -webkit- prefix see example below. You must also specify at least one of toprightbottom or left for sticky positioning to work. In this example, the sticky element sticks to the top of the page top: 0when you reach its scroll position. The z-index property specifies the stack order of an element which element should be placed in front of, or behind, the others. Because the image has a z-index of -1, it will be placed behind the text.
Note: If two positioned elements overlap without a z-index specified, the element positioned last in the HTML code will be shown on top. Set the shape of an element This example demonstrates how to set the shape of an element. The element is clipped into this shape, and displayed. If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:. Margins Margin Collapse. Float Clear Float Examples. Navbar Vertical Navbar Horizontal Navbar. Example div.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.The above code has been tested in the following browsers.
In order to explain how it works I have created a small sample. With this we come to an end this article you can download the sample source code using the download link given below.
Related Articles. Add Comments. Thank you for the feedback.
The comment is now awaiting moderation. You will be notified via email when the author replies to your comment. You can add your comment about this article using the form below. Make sure you provide a valid email address else you won't be notified when the author replies to your comment Please note that all comments are moderated and will be deleted if they are Not relavant to the article Spam Advertising campaigns or links to other sites Abusive content.