I'm programming in JavaScript and HTML , and I have a textArea
(textarea) , and a div
where I show that I resultado
have processed the content of the textArea
.
But what I want is to process the selected text . That is, he resultado
is:
Mark in bold and large size the selected part.
My code is the following:
function procesar_selección(texto)
{
return texto
}
function procesar_selección_html()
{
var texto = document.getElementById("texto_html").value
resultado.innerHTML = procesar_selección(texto)
}
textarea{
height: 100px;
width : 400px;
}
<div>Escriba el texto a procesar:</div>
<textarea
id = "texto_html"
onkeyup = "procesar_selección_html()"
onkeydown = "procesar_selección_html()" >
</textarea>
<div id="resultado" ></div>
To process the selected text , it is necessary to access two properties that the tag has
textArea
.selectionStart
is an integer indicating the position of the start of the selection .selectionEnd
is another integer, indicating the position of the end of that selection .First we make a function to get the
textarea
(the textarea) . For this we will usedocument.getElementById
and obtain the element that hasid
value"texto_html"
:In this case, you make a variable called
área_texto
and assign to it what the function returnsobtener_textarea()
, so thetextarea
will be the variableárea_texto
. We also do a similar function for the result area, we'll call itobtener_área_resultado()
.To access the
selectionStart
and propertiesselectionEnd
, simply doárea_texto.selectionStart
andárea_texto.selectionEnd
. Once the variables with these positions are declared, I do the following:This means that I am assigning the result of processing the selection to the center , along with the start of the text on the left , and the end of the text on the right . All of that built as a single plain text, which will be styled by the HTML
div
engine because I'm assigning it to a .The function
procesar_selección
, what it does is cut the text into three parts.The del
inicio
is from the beginning of what is written in the text area to the beginning of the selection.The del
centro
is from the start of the selection to the end of the selection.The del
fin
is from the end of the selection to the end of what is written in the text area.Finally, the three parts are concatenated, but the part of the is enclosed
centro
with labelsb
andbig
, so that it is displayed in bold and large .In addition to calling the function by pressing keyboard keys using
keydown
andkeyup
, I had it call the function by mouse movement, usingmousedown
,mouseup
andmousemove
. All of this is done with the propertyaddEventListener
.Full code: