'.on[event name] vs addEventListener
I tried to create copy handler but I couldn't.
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>test</title>
</head>
<body>
<h1>Test</h1>
<span class = "test"></span>
<script type = "text/javascript" src = "script.js"></script>
</body>
</html>
function handleCopy() {
document.querySelector("span.test").innerText = "Copied";
}
window.oncopy = handleCopy;
and I copy from index.html, but js doesn't change span. but changing the js code to like this, The span is change.
function handleCopy() {
document.querySelector("span.test").innerText = "Copied";
}
window.addEventListener("copy", handleCopy);
Why did that happen? Sorry my terrible English :(
Solution 1:[1]
This happens because there's no oncopy
property in window
object. If you'd open the console, and wrote "window.onco", there's no oncopy
in the suggestions. In the documentation this is not very clear, but when taking a look at Event handlers, oncopy
event is not listed, nor it can't be found on the following Event handlers implemented from elsewhere list. Instead, you can find it from Events list, which of prologue says: "Listen to these events using addEventListener()". It looks like the article needs a small fix, as the prologue says also that these events can be attached with oneventname
property, obviously that's not true in all cases.
Solution 2:[2]
The copy
event is not a GlobalEventHandler and thus doesn't have its own IDL handler available on window
.
This event is defined to fire on an HTMLElement and that's where the oncopy
IDL is accessible:
console.log("oncopy" in HTMLElement.prototype);
And because it's a DocumentAndElementEventHandler, you will also find it on document
.
So if you want to catch the event on the window
, that will be through bubbling and thanks to the addEventListener()
method.
addEventListener("copy", (evt) => {
console.log("copied");
});
<input value="copy me">
Otherwise, you can use document
's or any parent HTMLElement's event handler (e.g document.body
):
document.oncopy = (evt) => {
console.log("copied");
}
<input value="copy me">
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |