onselect Event select Javascript DOM Tutorial Share / Like
The select event fires when the target element has its text selected(highlighted by the user). It is commonly used to alter or save the portion of text that the user selects, as well as Rich Text Editor programming.
Scripting select events through Javascript and the DOM:
Javascript CODE EXAMPLE
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function addEventsToHTML(){
var ta = document.getElementById('ta');
ta.onselect = selectionHandler;
function selectionHandler(){
alert("select event dispatched for "+this.id);
}
}
window.onload = addEventsToHTML;
</script>
</head>
<body>
<textarea id="ta">Highlight some of this text</textarea>
</body>
</html>
Establishing select events direct on the html elements:
Javascript CODE EXAMPLE
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function selectionHandler(target){
alert("select event dispatched for "+target.id);
}
</script>
</head>
<body>
<textarea id="ta" onselect="selectionHandler(this);">Highlight some of this text</textarea>
</body>
</html>
TIP: In order to get the selected portion of text when a select event dispatches, research the getSelection() and createRange() methods. Internet Explorer is once again a thorn in our side for not adhering to the getSelection() method, so you must script 2 versions of your application to get selected text when a select event occurs thanks to Microsoft.