I suspect that your variable has nothing to do with the problem. The script in the external file works the very same way your inline script does. However, what I suspect is that you put the <script> element with the src-attribute for your external file into the <head> element, or otherwise insert it before the element which you want to get. That means that the JS is executed before the element even exists, hence the element cannot be found. Ideally, all script tags should be at the bottom of your HTML. Maybe you could post your complete code in codepen, so we can better point out the problem.
There are more issues with your code other than that, which I want to list so that you might write better code with fewer bugs in the future:
" which closes your string in the alert() call and a closing } for your try() function and () for the event handler function in the above code snippet. Also, your global variable has a different name than the variable you try to use inside the function. I recommend code highlighting and auto-complete in your editor and indenting your code in order to easily spot such problems.var, const or let before the name of any variable name you introduce.function(){} in order to encapsulate it.element.onclick = function(){} has the drawback that it can be overwritten by accident, so you should prefer element.addEventListener('click', function(){}) whenever possible.(function () {
const link = document.getElementById("element");
function setupLinkClickHandler() {
link.addEventListener("click", function() {
alert("hey");
});
}
})();
Some advanced tips and tricks, which might be interesting to have heard of, but you can put them aside for now if they seem too complicated or you just don't understand a word I write:
this. That's why I'd always prefer an arrow-function for handlers and callbacks, if possible.const variable, it cannot be overwritten, which results in getting rid of many very strange errors which might be hard to debug or a hassle to resolve.<script type="module" src="main.js"></script>, though.// import ...
const link = document.getElementById("element");
const setupLinkClickHandler = function() {
link.addEventListener("click", () => {
alert("hey");
});
}
// export ...