I am trying to add eventlistener for event loadstart on body of html page but it is not working.
Html code:
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rotate Text</title>
<script src="rotate_text.js"></script>
</head>
<body style="background-color:powderblue;">
</body>
</html>
Javascript code (rotate_text.js):
var body = document.getElementsByTagName("body")[0];
function populate_body() {
alert("Called");
} // end of populate_body
// body.onloadstart = populate_body(); // ====> THIS WORKS
body.addEventListener("loadstart", populate_body); // ====> THIS DOESN'T WORK
Why is addEventListener for event loadstart on body not working? Am I doing something wrong?
CodePudding user response:
The problem is that you call populate_body()
immediately when you assign it, that's why it worked :)
body.onloadstart = populate_body();
CodePudding user response:
The loadStart event occurs when the browser starts looking for the specified media and it can not applied on body element.
// body.onloadstart = populate_body(); // ====> THIS WORKS
This line of code doesn't add event listener, it shows the alert because you have called populate_body() function.
I'm not sure but maybe onl oad event is what is you are looking for.
function myFunction() {
alert('body element loaded')
}
document.body.onload = myFunction;