Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
91
rated 0 times [  95] [ 4]  / answers: 1 / hits: 16556  / 6 Years ago, wed, july 11, 2018, 12:00:00

I have an input field <input [email protected] type=text name=email id=email> and I want to make it so when a user focuses on this field, it will move the cursor to be before the @website.com.



I have the following Javascript/jQuery code but it does not seem to work:



$(document).ready(function() {
$(#email).focusin(function(){
$(#email).focus();
$(#email)[0].setSelectionRange(0,0);
});
});


It seems like the .focus() keeps calling the focusin() function.



I know $(#email)[0].setSelectionRange(0,0); is the proper way to move the cursor to the front but how do I bind it to when the field has focus?



Edit: So when I use:



$(#email).focus(function(){
$(#email)[0].setSelectionRange(0,0);
});


It sets the cursor to the beginning when I tab into the field but not when I click in.



Edit2: This is different than enter link description here because that just gets the caret position whereas I am looking to set the caret position.


More From » jquery

 Answers
13

This will bind the focus AND click events of the input field to the function. Hope this helps!





$('#email').on('focus click', function() {
$(this)[0].setSelectionRange(0, 0);
})

<script src=https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script>
<input type=text placeholder=Enter your name autofocus>
<input type=text id=email [email protected]>





Or, without jQuery...





document.getElementById('email').addEventListener('click', moveCursor);
document.getElementById('email').addEventListener('focus', moveCursor);

function moveCursor(event) {
event.target.setSelectionRange(0, 0);
}

<input type=text placeholder=Enter your name autofocus>
<input type=text id=email [email protected]>




[#54002] Sunday, July 8, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jazminuniquer

Total Points: 63
Total Questions: 121
Total Answers: 96

Location: Cambodia
Member since Thu, May 21, 2020
4 Years ago
;