+ 2
Help! Help!! I want to know why?
Happy new year everyone I have tried a recent code in javascript to generate random stories based on clicking the "Generate random story" button here is the code: https://code.sololearn.com/W1H2JSKf17TS But using sololearn it shows this message when i run it ========================================================= Uncaught TypeError: Cannot read property 'addEventListener' of null Line: 26 ========================================================= I retyped the code in sublime text and executed it successfully on my browser, as well as used other playgrounds like JSBin which executed successfully. Could this be a bug on the side soloLearn, or is there an error i need to fix?
5 Answers
+ 8
You're trying to access the DOM before it has been created. You need to wrap anything that accesses an element/tag of the web page in a window.onload function to ensure the code is ran after the DOM has been created. So wrap all your code in the JS tab in:
window.onload = function() {
// Place you code here
};
+ 12
your code problem is that it attempt to find elements in the HTML before it been completely loaded.
you should do something like this:
// declare variables
var customName = null;
var randomize = null;
var story = null;
// declare onload function (invoked after the HTML been completely loaded)
window.onload=function(){
// now you can get the elements from the HTML
customName = document.getElementById('customname');
randomize = document.querySelector('.randomize');
story = document.querySelector('.story');
randomize.addEventListener('click', result);
}
0
also case sensitivity,,JavaScript is case sensitive, var nameX is different from namex, try using exact variables as declared
0
Thanks @Burey and @ChaoticDawg. But why window.onload compulsory in this platform
0
it initiates the code immediately u run it,,its same as onload event included in the HTML of a page