Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
113
rated 0 times [  114] [ 1]  / answers: 1 / hits: 71127  / 11 Years ago, wed, august 21, 2013, 12:00:00

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();

More From » javascript

 Answers
62

You are not assigning your function to window.onload, you are calling your function, then assigning the result to window.onload



Replace window.onload = removeQuestions(); with window.onload = removeQuestions;



The browser expects a callback function to be in onload, so that it can call it whenever the window is loaded.



window.onload = removeQuestions();
is equivalent to



var result = removeQuestions(); // undefined, the function does not return anything
window.onload = result;

[#76234] Tuesday, August 20, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bruno

Total Points: 602
Total Questions: 100
Total Answers: 111

Location: Tajikistan
Member since Sun, Aug 29, 2021
3 Years ago
;