I’ve got some simple code inside a script tag in the body of my html doc which executes flawlessly:
<script type="text/javascript">
var anchor = document.getElementById("anchor");
function showCopy(e){
copyDiv.innerHTML = "this is the new copy!"
}
function addEvent(obj, evt, fn, capture){
if (onload.attachEvent){
obj.attachEvent("on" + evt, fn);
}
else{
if (!capture) capture = false;
obj.addEventListener(evt, fn, capture);
}
}
addEvent(anchor, "click", showCopy);
</script>
However, when I move it to an external js file – I get in the console:
"TypeError: Result of expression ‘onload’ [null] is not an object."
If I attempt to load the addEvent function with a window.onload handler:
addOnload(addEvent);
function addOnload(newFunction){
var oldOnload = window.onload;
if (typeof oldOnload == "function") {
window.onload = function(){
if (oldOnload){
oldOnload();
}
newFunction();
}
}
else{
window.onload = newFunction;
}
}
"obj" and "obj.addEventListener" throw TypeErrors in console.
Can anyone explain why it works in the script tag, but doesn’t in the linked file?
When you put it in the < body > does it come before or after the element anchor? The issue is that when you include the script file, the DOM hasn’t loaded yet, and anchor will be undefined. Options are to include the script file after anchor, or better yet after or do something like this (externally):