Search
Close this search box.
Search
Close this search box.

Use JavaScript to Set the Cursor Position in the Input

Curser Position in the input

Table of Contents

Use JavaScript to Set the Cursor Position in the Input

This article will teach you how to set the cursor to the end of text in text input elements using JavaScript.

To begin, we will create a text input box with a button that will move the pointer to the end and allow users to enter a value. This can be done using JavaScript by using several functions that are called when text finishes in text input elements.

Set Cursor

In the input basic project, where we will add an input field, JavaScript has already determined where the cursor is. To move the cursor to the end of the text, we can either drag it or click on the left end of the text.

To move the pointer in a new direction, use the keyboard’s right arrow. Thus, we’ll design a button to offer a basic user interface. The pointer is going to move to the end of the input text as soon as the user hits the button. We can type text more easily in the input area as a result.

We are going to work on a pretty simple project. The project will make use of fundamental JavaScript, HTML, and CSS ideas. This project is great for learning the fundamentals of form input, selecting JavaScript elements, and focus methods if you’re a novice.

Let’s get your project started. We’ll get our project’s outline ready.

Step 1: HTML Code For Input Box

				
					<body>
   <div class="container">
   <h1>Set cursor at end of elements demo</h1>
   <section>
      <p>Content Editable Div with Child nodes:</p>
      <div contenteditable="true" id="1" class="element" spellcheck="false">
         <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi sagittis sit amet est sed volutpat. Ut eu ipsum quam.</span><span> Nam at tellus eu mauris lacinia ultrices sed at elit. Sed suscipit lectus in diam viverra, at dapibus dui lobortis.
         </span>
      </div>
      <script>let element = document.getElementById("1")</script>
      <button onclick='setCarat(element)'>
      Set Cursor at end
      </button>
   </section>
   <section>
      <p>Textarea:</p>
      <textarea id="2" class="element" spellcheck="false">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi sagittis sit amet est sed volutpat.</textarea>
      <script>let element2 = document.getElementById("2")</script>
      <button onclick='setCarat(element2)'>
      Set Cursor at end
      </button>
   </section>
   <section>
      <p>Input:</p>
      <input id="3" class="element" value="Lorem ipsum dolor sit amet, consectetur adipiscing elit." spellcheck="false">
      <script>let element3 = document.getElementById("3")</script>
      <button onclick='setCarat(element3)'>
      Set Cursor at end
      </button>
   </section>
</body>
				
			

After we add structure to the project, we’ll need to include a few things in the link, such the fact that we’ve utilized many JavaScript and CSS files, which we must link to from our HTML files.

				
					//Head Section
<link rel="stylesheet" href="style.css">
//Body Section
<script src="script.js"></script>
				
			

We will now build an input box and use the value attribute inside it to add some text beforehand by utilizing the input tag with the type of text inside the body. We’ll also make a button to move the pointer to the finish using the button tag. We’ll make a link to advance the cursor to the end of the text using that button.

After adding the fundamental structure with HTML, let’s examine the result:

HTML Output

HTML Output

Step 2: CSS Code for Cursor Position

				
					* {
  box-sizing: border-box;
}

body {
  background: #DFD8DC;
}

body, p, div, textarea, input, button {
   color: #333;
  line-height: 1.5;
  font-family: sans-serif;
}

p {
  font-weight: bold;
}

section {
  padding: 15px;
  border-bottom: 1px solid #999;
}

.container {
  width: 50%;
  margin: 0 auto;
}

h1 {
  color: #9a7f94;
  border-bottom: 2px solid #9a7f94;
}

.element {
  border: 1px solid #ccc; 
  padding: 10px; 
  font-size: 14pt;
  background: #fff;
  border-radius: 5px;
}

textarea {
  height: 50px;
  width: 100%;
}

input {
  display: inline-block;
  min-width: 500px;
}

button {
  margin-top: 10px;
  padding: 10px;
  background: #B4BAD4;
  border: none;
  border-radius: 5px;
}

button:hover {
  background: #949dc3;
}
				
			

Step 1: We’ll set the background property to “misty rose” and the box size to “border-box” using the universal selector. We will select a font family of “sans-serif” and a line spacing of 1.5.

				
					* {
  box-sizing: border-box;
}

body {
  background: #DFD8DC;
}

body, p, div, textarea, input, button {
   color: #333;
  line-height: 1.5;
  font-family: sans-serif;
}
				
			

Step 2: The border-bottom property will now be set to 1 px solid black for the border bottom, and padding will now be set to 15 px using the section tag. Likewise, we’ll style the container with the class selector (.container). The width will be set to 50%, the left and right margins to auto, and the top and bottom margins to 0.

We will now change the border-bottom define to “wine,” which will result in a 2px solid line, and use the h1 tag selector to set the color to “wine

				
					section {
  padding: 15px;
  border-bottom: 1px solid #999;
}

.container {
  width: 50%;
  margin: 0 auto;
}

h1 {
  color: #9a7f94;
  border-bottom: 2px solid #9a7f94;
}
				
			

Step 3: Next, we’ll add a 1px wide, solid black border using the class selector (.element). Additionally, we’ll add 14px font size and 10px padding using the padding property. We’ll also add a margin-top of 10px and change the background color to a light blue tint using the button tag. To give our textarea distinct borders, we have additionally included a 5px border radius.

				
					input {
  display: inline-block;
  min-width: 500px;
}

button {
  margin-top: 10px;
  padding: 10px;
  background: #B4BAD4;
  border: none;
  border-radius: 5px;
}

button:hover {
  background: #949dc3;
}
				
			

CSS Output

Set Cursor

Step 3: Add JavaScript

				
					function setCarat(element) {
    // Place cursor at the end of a content editable div
    if (element.type !== "textarea" && element.getAttribute("contenteditable") === "true") {
        element.focus()
        window.getSelection().selectAllChildren(element)
        window.getSelection().collapseToEnd()
    } else {
        // Place cursor at the end of text areas and input elements
        element.focus()
        element.select()
        window.getSelection().collapseToEnd()
    }
}
				
			

All we’ll add to our JavaScript is the ability to click once to advance the cursor to the finish. The selectionEnd property will be used if the element type is a text field; if not, the element’s length will be used.

Using the window, we will use JavaScript’s getAttribute property to add focus to the element. Focus and selection methods will be added to the form input box if selectChildren() is not called; otherwise, functionality will be added.

Final Output

final result of the input’s cursor position being set:

We have now successfully written our JavaScript to set the input’s cursor location. We hope you have understood this project, and you are welcome to utilize it for your own webpage. Please leave a comment if you have any questions! If you find this blog useful, make sure to follow on Instagram and run a Google search for “cssiseasy” to locate front-end projects with source code.

Code by: Shakima

Project Link – Codepen

Written by: cssiseasy

Facebook
Twitter
LinkedIn
Telegram
Email
WhatsApp

Leave a Comment

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

Scroll to Top