CSS Portal

HTML onselect Event Attribute

If this site has been useful, we’d love your support! Consider buying us a coffee to keep things going strong!

Description

The HTML onselect event attribute fires after some text has been selected in an element. It is mostly used on <input type="text"> or <textarea> elements, but can also be used on other elements, such as <div> and <span>.

When the user selects text in an element with the onselect attribute, the specified JavaScript function is executed. The function can be used to perform any task, such as displaying a message, updating the DOM, or making a server request.

Here is an example of how to use the onselect event attribute:

<input type="text" onselect="myFunction()">

The myFunction() function will be executed whenever the user selects text in the <input> element.

The onselect event attribute can be used to create a variety of interactive web applications. For example, you could use it to create a text editor that highlights selected text, or a web form that validates selected text before submitting the form.

Here are some examples of how the onselect event attribute can be used:

  • To display a message when the user selects text in an element:
function myFunction() {
  alert("You selected the text: " + window.getSelection().toString());
}
  • To update the DOM when the user selects text in an element:
function myFunction() {
  var selectedText = window.getSelection().toString();
  document.getElementById("myElement").innerHTML = selectedText;
}
  • To make a server request when the user selects text in an element:
function myFunction() {
  var selectedText = window.getSelection().toString();
  var xhr = new XMLHttpRequest();
  xhr.open("POST", "/my-server-endpoint");
  xhr.setRequestHeader("Content-Type", "application/json");
  xhr.send(JSON.stringify({ selectedText }));
}

Syntax

<element onselect="script">

Values

  • scriptThe name of the script to use when the event has been triggered.

Example

<!DOCTYPE html> 
<html>
<head>
<title>onselect event</title>
</head>
<body>
<textarea rows="5" cols="40" onselect="testFunction()">You just need to select the text to run the script ...</textarea>
<script>
function testFunction () {
alert ( "EXAMPLE: You ran the script!" );
}
</script>
</body>
</html>

Browser Support

The following information will show you the current browser support for the HTML onselect event attribute. Hover over a browser icon to see the version that first introduced support for this HTML event attribute.

This event attribute is supported by all modern browsers.
Desktop
Chrome
Edge
Firefox
Opera
Safari
Tablets & Mobile
Chrome Android
Firefox Android
Opera Android
Safari iOS
Samsung Internet
Android WebView
-

Last updated by CSSPortal on: 14th October 2023

If this site has been useful, we’d love your support! Consider buying us a coffee to keep things going strong!