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