Home > Software engineering >  .on[event name] vs addEventListener
.on[event name] vs addEventListener

Time:02-02

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 :(

CodePudding user response:

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 prolog says: "Listen to these events using addEventListener()". It looks like the article needs a small fix, as the prolog says also that these events can be attached with oneventname property, obviously that's not true in all cases.

CodePudding user response:

with the addEventListener you can add several times an event on an element, while the on... will overwrite each time the old one so that you have only one event left

  •  Tags:  
  • Related