I would use a javascript or jquery function as you like, in this case, as your question has the jquery tag, I decided to make a function with jquery
One of the functions I did was detect the click
$('div').on('click',function(){
//validación para agregar espacio al inicio solo si hay una función x/x
if($(this).html().slice(0,1) == "<"){
var text = $(this).html();
var val = $(this).html("").append(" " + text);
//este es el segundo click pero no funciona
setCursorToEnd($(this).get(0));
}
//Validación para agregar espacio al final solo di hay una función x/x
if($(this).html().slice(-1) == ">"){
var val = $(this).append(" ");
//este es el segundo click pero no funciona
setCursorToEnd($(this).get(0));
}
});
Then it was to position the focus until the end based on this SOen question
function setCursorToEnd(ele)
{
var range = document.createRange();
var sel = window.getSelection();
range.setStart(ele, 3);//cambiando 1 por 3 para dejar el cursor después del espacio.
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
ele.focus();
}
Your sample code working:
$('div').on('click',function(){
//validacion para agregar espacio al inicio solo si hay una funcion x/x
if($(this).html().slice(0,1) == "<"){
var text = $(this).html();
var val = $(this).html("").append(" " + text);
//este es el segundo click pero no funciona
setCursorToEnd($(this).get(0));
}
//Validacion para agregar espacio al final solo di hay una funcion x/x
if($(this).html().slice(-1) == ">"){
var val = $(this).append(" ");
//este es el segundo click pero no funciona
setCursorToEnd($(this).get(0));
}
});
function setCursorToEnd(ele)
{
var range = document.createRange();
var sel = window.getSelection();
range.setStart(ele, 3);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
ele.focus();
}
.fraccion
{
display:inline-block;
font-size: 90%;
text-align: center;
vertical-align: middle;
padding: 0 .1em;
}
.denominador
{
border-top: 1px solid;
float: right;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style='border: 1px solid darkgray; width:200px' contenteditable>
hola
<span class='fraccion'>
<span>5</span>
<span class='denominador'>
<span>4</span>
</span>
</span>
hola
</div>