EN
JavaScript - onselect event example
0 points
In this article, we would like to show you onselect
event example in JavaScript.
Quick solution:
xxxxxxxxxx
1
var myElement = document.querySelector('#my-element');
2
3
myElement.addEventListener('select', function() {
4
console.log('onselect event occurred.');
5
});
or:
xxxxxxxxxx
1
<input type="text" onselect="handleSelect()" value="Example text to select.">
or:
xxxxxxxxxx
1
var myElement = document.querySelector('#my-element');
2
3
myElement.onselect = function() {
4
console.log('onselect event occurred.');
5
};
There are three common ways how to use onselect
event:
- with event listener,
- with element attribute,
- with element property.
In this section, we want to show how to use onselect
event on input
element via event listener mechanism.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<input type="text" id="my-input" value="Select this text.">
5
<script>
6
var myInput = document.querySelector('#my-input');
7
8
myInput.addEventListener('select', function() {
9
console.log('onselect event occurred.');
10
});
11
</script>
12
</body>
13
</html>
In this section, we want to show how to use onselect
event on input
element via attribute.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<input type="text" onselect="handleSelect()" value="Select this text.">
5
<script>
6
function handleSelect(){
7
console.log('onselect event occurred.');
8
}
9
</script>
10
</body>
11
</html>
In this section, we want to show how to use onselect
event on input
element via property.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<input type="text" id="my-input" value="Select this text.">
5
<script>
6
var myInput = document.querySelector('#my-input');
7
8
myInput.onselect = function() {
9
console.log('onselect event occurred.');
10
};
11
</script>
12
</body>
13
</html>