Question

I used some JS API to make some charts. In the code there is already window.onload = function (){}, now I want to have keydown event for a canvas. Does anybody know where to add the code? It seems pretty silly but I just cannot get information about the window.onload's effect for the js action.

Was it helpful?

Solution

You can use a DOM2 handler instead:

window.addEventListener("load", function() { /*...your code here...*/}, false);

On IE8 and earlier, you have to handle the fact that they don't have it:

if (window.addEventListener) {
    window.addEventListener("load", function() { /*...your code here...*/}, false);
}
else if (window.attachEvent) {
    window.attachEvent("onload", function() { /*...your code here...*/});
}

DOM2 handlers sit alongside the old DOM0 handlers, without interfering with them. The big advantage they offer is that you can have multiple handlers for the same event, so this issue (of there already being a handler) doesn't come up.


Side note: The load event on window happens really late in the page load process, after all external resources have complete loaded (or failed to). 99% of the time, it's better to just put your code in a script at the end of the body, just before the closing </body> tag, like this:

<!-- ...content... -->
<script src="yourscript.js"></script>
</body>
</html>

Then you don't need to hook the load event at all, because all of the DOM elements defined by the markup above already exist. Just have your code run immediately.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top