Getting cursor position javascript

How to find the coordinates of the cursor with JavaScript?

In this tutorial, we will learn how we can find the coordinates of the mouse cursor with JavaScript. We have to find out the X and Y-coordinates or we can say that the horizontal and the vertical position of the cursor on the screen with JavaScript.

JavaScript provides us with two different properties to get the coordinates of the mouse cursor when the mouse button is pressed anywhere on the screen −

Using event.clientX Property

The event.clientX property is used to find out the value of the horizontal position or the X-coordinate of the cursor where the event was triggered. It returns a numeric value that specifies the horizontal position of the cursor.

Syntax

Following is the syntax to get the horizontal position of the cursor −

function function_name(event)

Steps

Step 1 − In step one, we need to define the callback function that performs some activity when the event triggers.

Step 2 − In the second step, we will declare a variable and assign it a value using event.clientX property, that returns the horizontal or the X-coordinate of the cursor position.

Step 3 − This step contains the statements that are required to display the returned value on the screen that is stored in the variable declared in last step.

Example

Below example illustrates how we can get the X-coordinate of the cursor using JavaScript −

!DOCTYPE html> html onclick="display(event)"> body> h3>Find the coordinates of the cursor with JavaScript/h3> p id="para">Click anywhere on the screen to see X-coordinate of the cursor using "event.clientX" property./p> p id="result">/p> script> function display(event) let X = event.clientX; let result = document.getElementById("result"); result.innerHTML = "X-coordinate: " + X; > /script> /body> /html>

In this example, we find out the position of the cursor on X-axis or in horizontal direction using the event.clientX property.

Using event.clientY Property

It is used to find out the position of the cursor in the vertical direction or on the Y-axis where the event was triggered. Similar to the event.clientX property, it also returns a numeric value that holds the position of the cursor on the Y-axis or Y-coordinate.

Syntax

Following is the syntax to use event.clientY property to get the Y-coordinate of cursor using JavaScript −

function function_name(event)

Steps

Step 1 − In step one, we will define the callback function that performs some activity on the webpage when the event triggers.

Step 2 − In second step, we will declare a variable and assign it a value using the event.clientY property, that returns the vertical or the Y-coordinate of the cursor position.

Step 3 − This step includes the statements that are required to display the returned value of the cursor position on the Y-coordinate or in the vertical direction on the screen that is stored in the variable declared in the last step.

Example

Below example illustrates how we can get the X-coordinate of the cursor using JavaScript −

!DOCTYPE html> html onclick="display(event)"> body> h3>Find the coordinates of the cursor with JavaScript/h3> p id="para">Click anywhere on the screen to see Y-coordinate of the cursor using "event.clientY" property./p> p id="result">/p> script> function display(event) let Y = event.clientY; let result = document.getElementById("result"); result.innerHTML = "Y-coordinate: " + Y; > /script> /body> /html>

In this example, we have find out the Y-coordinate of the cursor using The event.clientY property of JavaScript.

Let us understand how we can find out the position of the cursor on a 2D plane using both properties in the same example.

Steps

Step 1 − In step one, we will define the callback function that performs some activity on the webpage when the event triggers.

Step 2 − In second step, we will declare two variables and assign them values using the event.clientX and the event.clientY properties, which return the horizontal and the vertical or the X and the Y-coordinates of the cursor position on the screen.

Step 3 − This step includes the statements that are required to display the returned value of the cursor position on the Y-coordinate or in the vertical direction on the screen that is stored in the variable declared in the last step.

Example

Below example illustrates how we can get the X-coordinate of the cursor using JavaScript −

!DOCTYPE html> html onclick="display(event)"> body> h3>Find the coordinates of the cursor with JavaScript/h3> p id="para">Click anywhere on the screen to see X and Y-coordinate of the cursor using JavaScript properties./p> p id="result">/p> script> function display(event) let X = event.clientX; let Y = event.clientY; let result = document.getElementById("result"); result.innerHTML = "X-coordinate: " + X + "
Y-coordinate: : "
+ Y; > /script> /body> /html>

In above example, we have used the event.clientX and event.clientY properties simultaneously to find out the position of cursor on 2D plane using JavaScript.

In this tutorial, we have learnt about the JavaScript properties to find out the coordinates of the cursor with help of individual and a example where we used both the properties to find the position of cursor on 2D plane or X and Y-coordinates simultaneously.

Источник

How to Get the Cursor Position in JavaScript

To get the cursor position in JavaScript, we can use the MouseEvent client properties, that is the clientX Property and the clientY Property.

event.clientX event.clientY

To get the cursor position we will need to attach a mouse event to either a div on the page or to the whole page document itself. We will need to attach a function to that event, and then use the function to get the position of the cursor.

A good event to use to get the position of the cursor is the onmousemove event. Whenever a user moves their mouse on the specified element, the onmousemove event will be triggered. We can then call a function, and the important part, we will pass in a parameter to the function, that will contain information about our cursor.

Here is the HTML setup we can use for the first part of getting the cursor position.

As you can see in the code above, we attach the function getCusorPosition and pass it a parameter we call event. We will use this in the next and final part below.

function getCursorPosition(event)

As we can see from the code above in our function, we take the parameter that has been passed to us called event and get the properties clientX and clientY of it.

We put these together to get the cursor position. Let’s take a look at this in action below.

How to Get and Display the Cursor Position in JavaScript

In this example, we will create a div that takes up a section of the page. We will then add the onmousemove event to the div to run a function to help us get the X and Y coordinates of the cursor. The user will have to move their mouse in this div for us to get this information.

Finally, we will have two divs below where we can display the x and y positions of our cursor to the user.

In our function getCursorPosition, we will use the parameter that has been passed to us to get the x and y coordinates of the cursor. To get the x coordinate of the cursor, we will use the clientX property. To get the y coordinate of the cursor, we will use the clientY property.

We will finally use the textContent property to display the results to the user.

And that’s it. Here is the JavaScript code:

function getCursorPosition(event)

The final code and output for this example is below:

Источник

How to get the current cursor position (and selection) within a text input or textarea in Javascript

Carlos Delgado

Learn how to get the position of the cursor within a text box or a text area easily with Backward browser compatibility in Javascript.

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.

The typical way

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.

IE < 8 support

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 ).

/** * Return an object with the selection range or cursor position (if both have the same value) * @param el A dom element of a textarea or input text. * @return reference Object with 2 properties (start and end) with the identifier of the location of the cursor and selected text. **/ function getInputSelection(el) < var start = 0, end = 0, normalizedValue, range, textInputRange, len, endRange; if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") < start = el.selectionStart; end = el.selectionEnd; >else < range = document.selection.createRange(); if (range && range.parentElement() == el) < len = el.value.length; normalizedValue = el.value.replace(/\r\n/g, "\n"); // Create a working TextRange that lives only in the input textInputRange = el.createTextRange(); textInputRange.moveToBookmark(range.getBookmark()); // Check if the start and end of the selection are at the very end // of the input, since moveStart/moveEnd doesn't return what we want // in those cases endRange = el.createTextRange(); endRange.collapse(false); if (textInputRange.compareEndPoints("StartToEnd", endRange) >-1) < start = end = len; >else < start = -textInputRange.moveStart("character", -len); start += normalizedValue.slice(0, start).split("\n").length - 1; if (textInputRange.compareEndPoints("EndToEnd", endRange) >-1) < end = len; >else < end = -textInputRange.moveEnd("character", -len); end += normalizedValue.slice(0, end).split("\n").length - 1; >> > > return < start: start, end: end >; > 

You can use it easily using the previous function (remember to focus the input using the focus method to prevent any error):

var element = document.getElementById("someID"); // Focus element, in case that it's not element.focus(); var result = getInputSelection(element); console.log(result); // < // start: 5, // end: 5 // >

And see a live example in the following fiddle:

The previous snippet was published in StackOverflow and the one who answered, created a repository with MIT license. The mini library is a wrapper made in jQuery for tipical tasks related to the text selection and position within a text input or textarea element (getSelection, setSelection, deleteText etc).

Conclusions

  • If the start and end value are the same, it means that there’s no selected text and the start value (or end value) is the position of the cursor.
  • Note that in IE the textarea or text input must have the focus before calling the mentioned method. You can ensure this by calling the focus() method of the element (or its jQuery object).

Источник

How to Get Cursor Position in JavaScript

How to Get Cursor Position in JavaScript

If you ever had a specific case where you had to retrieve the position of a caret (your cursor’s position) inside an HTML input field, you can do so using the selectionStart property of an input’s value.

input type="text" id="input" value="123" /> script> const input = document.getElementById('input'); const position = input.selectionStart; // If the position of the cursor is at the very last character inside the input, // this will result in 3 alert(position); script>

You can also outsource this functionality to the following one-line function, to reuse it across your application:

const getCaretPosition = e => e && e.selectionStart || -1; getCaretPosition(document.getElementById('input')); // Returns 3 getCaretPosition(document.getElementById('email')); // Returns -1

Keep in mind that selectionStart can only be retrieved from the following list of input types:

Therefore, in the example above, if you try to use it on an email type, it will always return -1.

How to Get Caret Position with JavaScript?

Get your weekly dose of webtips

Level up your skills and master the art of frontend development with bite-sized tutorials.

We don’t spam. Unsubscribe anytime.

Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.

Resources

Get your weekly dose of webtips

📚 More Webtips

Level up your skills and master the art of frontend development with bite-sized tutorials.

We don’t spam. Unsubscribe anytime.

  • Unlimited access to hundreds of tutorials
  • Access to exclusive interactive lessons
  • Remove ads to learn without distractions

How to Darken Background to Give Focus

How to Darken Background to Give Focus

How to Make Custom Bullet Points With CSS

How to Make Custom Bullet Points With CSS

How to Get Tomorrow's Date in JavaScript

How to Get Tomorrow’s Date in JavaScript

Get your weekly dose of webtips

Get access to 300+ webtips 💌

Level up your skills and master the art of frontend development with bite-sized tutorials.

We don’t spam. Unsubscribe anytime.

Источник

Читайте также:  Os mkdir mode python
Оцените статью