I found javascript code that allows me to add html tags around text that I have highlighted in the textarea
field:
<textarea id="myArea" cols="30" spellcheck="false">Select some text within this field.</textarea>
<button onclick="ModifySelection ()">Modify the current selection</button>
<script>
function ModifySelection () {
var textarea = document.getElementById("myArea");
if('selectionStart' in textarea){
if (textarea.selectionStart != textarea.selectionEnd) {
var newText = textarea.value.substring (0, textarea.selectionStart) +
"[start]" + textarea.value.substring (textarea.selectionStart, textarea.selectionEnd) + "[end]" +
textarea.value.substring (textarea.selectionEnd);
textarea.value = newText;
}
}
}
</script>
My questions pertain to this line, if('selectionStart' in textarea){
:
selectionStart
have to be in quotes?selectionStart
is usually appended to an object like
"textarea"(textarea.selectionStart)
, how is it possible to refer
to
it by itself?If(X in Y){}
standard javascript syntax or does it work
specifically forselectionStart
?note: I'm testing this in jsfiddle
if('selectionStart' in textarea)
is feature testing - it checks whether the textarea
object has a selectionStart
property.
It needs to be in quotes as otherwise it would be interpreted as a variable (which may or may not exist in the current context).
It depends on the browser and what version of HTML is supported and rendered.
Yes it is normal javascript syntax. It is used to test if the specified property is in the object. See in
on MDN.