2
I’m making a simple virtual keyboard:
https://codepen.io/anon/pen/qGvweN
But I can’t identify the position of the pointer in the field, every time I type the letter it only comes out at the end, even though I set it to come out at the beginning, what the logic is for me to be able to put the typed letter always where the pointer has placed and not always at the end as in this example?
<style>
.teclas span {
display: inline-block;
position: relative;
background: #000;
font-size: 20px;
cursor: pointer;
width: 54px;
height: 38px;
border-radius: 5px;
margin: 0 7px 11px 0;
color: #fff;
line-height: 40px;
text-align: center;
}
</style>
<script src='//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script>
$(document).ready(function(){
$('#teclado div span').click(function(){
var palavra = $(this).text();
if (palavra == ''){
$('#email').val($('#email').val().substr(0, $('#email').val().length - 1)).focus();
} else {
$('#email').val($('#email').val() + palavra).focus();
}
});
});
</script>
<input id="email" type="text" value=".gmail.com" autofocus>
<br /><br />
<div id="teclado">
<div class="teclas">
<span>A</span>
<span>B</span>
<span>C</span>
<span>D</span>
<span>E</span>
<span>F</span>
<span>G</span>
<span>H</span>
<span>I</span>
<span>J</span>
</div>
</div>
To know where the cursor is, you can use the input.selectionStart. Original answer for example: https://stackoverflow.com/questions/2897155/get-cursor-position-in-characters-within-a-text-input-field/48150864#48150864
– JDuwe