Javascript scroll to cursor position

Get Cursor Position in JavaScript

  1. Use selectionStart and selectionEnd Property to Get Cursor Position
  2. Use screenX/Y Properties to Get Cursor Position
  3. Use clientX/Y to Get Cursor Position
  4. Use pageX/Y Property to Get Cursor Positional Value

JavaScript was incorporated with the fundamental positional property selectionStart and selectionEnd , where we can only retrieve the positional value from a string literal’s 0th index. Other properties also play a vital role in extracting the positional values based on coordinate marks.

In this case, the reference point can vary and thus results in different values respective to different frames. The following section will demonstrate examples of the selectionStart and selectionEnd properties.

We will also consider the working principle for the screenX/Y , clientX/Y , and pageX/Y , where three properties are based on coordinate systems. But, first, let’s jump into the main part!

Use selectionStart and selectionEnd Property to Get Cursor Position

The selectionStart and selectionEnd properties are read/write properties. You can either define them with a positional value or take the default value, which performs the read operation.

There is also the getSelectionRange property that explicitly takes the selectionStart and selectionEnd values and figures out a specific range of sub-string. Playing with strings is limited as they only work on some particular attributes.

For example, input:text , input:textarea , input:password , and etc. You can have a more detailed aspect in this particular documentation. In the instance demonstrated here, we will only showcase the read-only method for the selectionStart .

When talking about the read-only convention, the selectionStart and selectionEnd will perform similarly. It prints the position of the string character that the cursor has passed.

To be precise, the cursor is the text type cursor on which these properties work. And so, we only get the position of the horizontal part, and the calculation is dependent on the character counts. So let’s check how it works.

 html> head>  meta charset="utf-8">  meta name="viewport" content="width=device-width">  title>Get Cursortitle>  head> body>  input id="Javascript_example" name="one" type="text" value="Javascript example" onmousemove="textbox()">  p id="vals">p>  script>  function textbox()  var ctl = document.getElementById('Javascript_example');  var startPos = ctl.selectionStart;  document.getElementById('vals').innerText = startPos;  >  script>  body>  html> 

The selectionEnd would perform similarly here, so we didn’t add any preview. You can try and see the same outcome as the selectionStart property. It is the read-only section of these properties.

Use screenX/Y Properties to Get Cursor Position

In the case of the screenX/Y property, we calculate the position referred by a reference point. The coordinate value strictly follows a certain referral point to show the position.

Читайте также:  Mysql select query in java

Here, the cursor position is for the default cursor; thus, we will use the onmousemove attribute to track the positions. The screenX/Y is a read-only property, and it follows the reference point as the global or the whole screen coordinate. Let’s check the example below.

 html>  head>  title>Get Cursortitle>  head>  body>  p>Move your mouse to see its position.p>  p id="screen-log" style="height:900px;width:600px; text-align:center">p>  body>  script>  let screenLog = document.querySelector('#screen-log');  document.addEventListener('mousemove', logKey);   function logKey(e)   screenLog.innerText = `  Screen X/Y: $e.screenX>, $e.screenY>`;  >  script>  html> 

As can be seen, the coordinate values are updated on the cursor’s moving position. Also, in one section, you will notice that scrolling does not affect the cursor’s position.

It means that whenever a page is scrolled up-down or left-right, the whole page gets frozen and calculates the position for that instance of the frame considering the screen size.

Use clientX/Y to Get Cursor Position

The clientX/Y is also a read-only property with the reference point as the viewport. In this regard, the scrolled up-down viewport is kept statue, and the coordinate values are measured.

More clearly, if you are in the top section of your page, then the y value would be 0 . And supposedly, you have scrolled down to 20 pixels, and if you try to retrieve the y value, it will still show it as 0 .

It means whatever portion is occupying the viewport, only that is taken under consideration.

 html>  head>  title>Get Cursortitle>  head>  body>  p>Move your mouse to see its position.p>  p id="screen-log" style="height:900px;width:600px; text-align:center">p>  body>  script>  let screenLog = document.querySelector('#screen-log');  document.addEventListener('mousemove', logKey);   function logKey(e)   screenLog.innerText = `  Client X/Y: $e.clientX>, $e.clientY>`;  >  script>  html> 

So, in the portion where we checked the page’s top value(y) , it resulted in 0 . And when scrolled down a little, the value remained 0 . So, we can do a similar task for the x-axis value.

Use pageX/Y Property to Get Cursor Positional Value

Similar to screenX/Y and clientX/Y , pageX/Y is also a read-only property. But unlike those properties, pageX/Y considers the whole page’s dimension while calculating values.

It means if the viewport has a larger length than the viewport that is screened on, the property will count for the whole dimension of the entire page. Thus we can fetch important sections or cursor positions more intuitively through this property.

 html>  head>  title>Get Cursortitle>  head>  body>  p>Move your mouse to see its position.p>  p id="screen-log" style="height:900px;width:600px; text-align:center">p>  body>  script>  let screenLog = document.querySelector('#screen-log');  document.addEventListener('mousemove', logKey);   function logKey(e)   screenLog.innerText = `Page X/Y: $e.pageX>, $e.pageY>`;  >  script>  html> 

As can be visualized, when we have not scrolled the scrollbar, the top position value of the y-axis was 0 .

And when we scrolled down a bit, the top showed the y value as the number of pixels that have been scrolled down to, which is 58 . So now, we can go for a comparative discussion on which property is more suitable depending on the work purpose.

Era is an observer who loves cracking the ambiguos barriers. An AI enthusiast to help others with the drive and develop a stronger community.

Читайте также:  Лейси н python например

Related Article — JavaScript Cursor

Источник

Scroll to cursor when textarea rows become less in javascript

Unless the textarea has a special purpose, I wouldn’t bother with the append-on-focus function. Question: I want to get the cursor offset (not the cursor position) from the top of the view of a textarea.

Scroll to cursor when textarea rows become less in javascript

I want the textarea to scroll to cursor once the row number has been changed.

Sometimes when I change the row number reducing it the cursor goes out of view

How do I make it so that the cursor stays in view?

startPos = ta.selectionStart; const endPos = ta.selectionEnd; newText = ""; ta.blur(); ta.focus(); ta.setRangeText(newText, startPos, endPos, 'end'); ta.rows = "6"; 

The textarea is originally 26 rows big, I resize it using javascript onfocus event to 6 rows. However, when the cursor is in a position that is somewhere over 6 rows when I resize it is not shown unless I manually scroll to it.

I managed to do this by customising the jsfiddle on this answer https://stackoverflow.com/a/40951875/10801626

const index = ta.selectionStart; //instead of getting the indexOf as shown in the link shared above, I get the selectStart ta.selectionStart = ta.selectionEnd = index; ta.blur(); ta.focus(); ta.selectionStart = index; ta.selectoonEnd = index; //I also customised this line removing the "Hello World".length 

Hopefully this can help someone else too.

Howto Place cursor at beginning of textarea, 6. Depending on your needs, a simpler Javascript version is: document.querySelector («textarea»).focus (); //set the focus — cursor at end …

Scroll an input box to the cursor position in javascript

I’ve written a simple JS function that places the cursor at the end of the contents of an input box when it receives focus (the most common action in the box being to append). I haven’t checked in IE, but when there is more text than is visible, even moving the cursor to the end of input doesn’t scroll the view to the end of input in firefox 3.6.

P.S. And no I’m not using JQuery, nor is it an option 😉

Found a solution here using different wording (caret instead of cursor)

You can scroll by assigning to the textarea’s scrollTop property:

// scroll to bottom elt.scrollTop = elt.scrollHeight; 

Firefox and Safari also offer scrollByLines , and IE has doScroll , but the scrollTop property is cross-browser and simpler to use.

Personally, I don’t like it when the cursor is moved for me to the end of a textarea. If I want it at the end, it takes a fraction of a second to do it my self. It takes around a second to move the cursor from the end to somewhere in the middle (the end is a larger target, thus takes less time to hit). Unless the textarea has a special purpose, I wouldn’t bother with the append-on-focus function.

How to preserve cursor position on textarea text change?, May 6, 2015 at 16:48. Add a comment. 2. You can use selectionStart prop as described here to store and then reset cursor position. var …

Scrolling textarea to specific area with javascript

I have a textarea with a scrollbar. I need to change the position of your Cursor in the textarea with javascript AND scroll the textarea so your cursor is visible. I am using elem.selectionStart and elem.selectionEnd to move your cursor, but when I move it to a point that is not visible, the textarea does not scroll so the cursor is visible.

Читайте также:  Растянуть фон во весь экран html

More details (probably TL;DR) I am creating a slideshow editor and have a preview of the complete slideshow next to an editor (textarea with scrollbar) for the content. As you move your cursor through the textarea, the slideshow changes slides so you are always viewing the slide that you are editing. I need to get it so changing the slide (using buttons) moves your cursor so you can see the code that generated that slide.

// slideBoundries has numbers which are the indexes where the slides begin/end // eg: [0, 81, 140, 250] for slideshow with 3 slides if (doc.editor.selectionEnd > slideBoundries[curSlide] && doc.editor.selectionEnd < slideBoundries[curSlide + 1]) < return; >doc.editor.selectionStart = slideBoundries[curSlide]; doc.editor.selectionEnd = slideBoundries[curSlide]; 

I could just count the number of newlines in the file so I know how far to scroll down, but there are many lines that are long and take up multiple lines. I am using a monospaced font so counting the number of newlines and lines that take up multiple lines, but I would like an easier way. Is there a function I could call to mimic what happens when the user moves their cursor as the textarea always scrolls to that point when the user clicks.

EDIT: Due to popular demand, here is a fiddle: http://jsfiddle.net/tShQ2/

The method I’m going to use to fix this issue is create a phantom textarea that has same width, but autosizes to height. It has to be visible or else it won’t work, so make it abs position and move it off screen. Then put the text before the desired cursor position in it. Then scroll the real textarea to the height of the phantom textarea.

Your solution is a good one, but let me suggest a couple of things to make it easier.

  1. Use a phantom div, rather than a textarea, since a div will autosize automatically. Just make sure to match the styles.
  2. To hide your phantom div use: visibility: hidden;
    position: absolute; This has the same effect as display: none , while allowing the div to have a height.

One more thing. For IE, you can create a range from the selection and scroll to it explicitly:

document.selection.createRange().scrollIntoView(); 

JQuery: scroll textarea to given position, How can I do this using javasctipt/jQuery? $(‘#txt’).scrollToCharNo(2000); // something like this would be great EDIT (my …

How to get the offset of the cursor position from the visible area

I want to get the cursor offset (not the cursor position) from the top of the view of a textarea.

e.target.selectionStart gives me the cursor position. $el.scrollTop gives me the scroll offset of the textarea.

How do I calculate the offset into the visible area of the cursor?

hope what you want is what i’ve understood, which is you want to get the offset of the mouse inside text area ignoring the scroll position, here is an example:

const area = document.getElementById("textarea"); area.addEventListener("click", (e) => < var ofsetY = e.offsetY; >); 

How to get X Y position of scroll/mouse/cursor of, I am using CKEDITOR 4. How to find out the scroll/mouse/cursor X Y position ( not of the window )? I’ve tested the below code but its giving the …

Источник

Оцените статью