Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

External JS with onLoad Event

I have an external js file which has a function that is meant to run AFTER the document body has loaded. This is what I have so far but it's not working as it should. Some help please.

External JS File

window.document.body.addEventListener('load', numOfSelects());

function numOfSelects()
{
  var selects = document.getElementsByTagName('select');
  alert(selects.length);
}

The HTML file that calls this script does have a few select fields. The alert works but it shows 0. And after the alert shows then the body can be seen loaded. Obviously this is not what I wanted. What am I doing wrong? Thanks guys.

I have also tried this:

Still didn't work. Here's my code:

Parent File

<html>
<head>
<title>File 1</title>
<script src='file1.js'></script>
</head>

<body>

<select id='dd1'><option>First</option><option>Second</option></select>
<select id='dd2'><option>First</option><option>Second</option></select>

</body>
</html>

JS FILE

alert('start');
window.document.body.addEventListener('load', function(){alert(document.getElementsByTagName('select').length)}); 
alert('stop');

only the first alert shows. I feel like I have made a really silly error somewhere.

like image 717
Craig Wayne Avatar asked Dec 27 '22 01:12

Craig Wayne


1 Answers

You simply want

window.addEventListener('load', numOfSelects);

like image 74
theaceofthespade Avatar answered May 16 '23 06:05

theaceofthespade