Hi I'm new to Javascript and I'm trying to get a function to remove some elements once the window has loaded.
Here is the HTML
<html>
<head>
<title>Simple Quiz</title>
<script type="text/javascript" src="script.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>Quiz</h1>
<h2>Question</h2>
<p id="question"></p>
<form name="choices">
<fieldset>
<!-- insert questions here dynamically via javascript! -->
<label><input type="radio" name="choice" value="1st">First-class</label>
<label><input type="radio" name="choice" value="2day">2-day Air</label>
<label><input type="radio" name="choice" value="overnite">Overnight</label>
</fieldset>
</form>
</body>
</html>
The function removeQuestions() works fine when called in the console after the page has loaded but I can't seem to get it to work using the onload event for the window. Interestingly enough, it works on JSFiddle (found here) but not when I fire up the page locally in chrome. What am I not getting right? Thank you
Here is the script.js file:
// JS executed after window has been loaded
function removeQuestions() {
var choices = document.forms.choices.elements[0].children;
// remove choices
while (choices.length > 0) {
var choice = choices[0];
choice.parentNode.removeChild(choice);
}
}
window.onload = removeQuestions();
To simplify, thats how the callback should look like:
window.onload = (event) => {
console.log('page is fully loaded');
removeQuestions();
};
In my case it did not work because I had set window.onload
in two scripts running on the same page. It took me time to realise this mistake because the first script had console.log messages but the second script did not have any. Browser loaded the second script after first script and my window.onload = somefunction was now set to a function without any console.log giveing me the impression that it is not working at all
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With