In this article, we will look at page events and how JavaScript handle those events.
Load Event
JavaScript can check the page level events such as load. Once the DOM tree is ready, we can call the HTML elements and manipulate them.
For example:
<body onload = "init()">
<p>Page Status:<span id="status">NOT LOADED</span></p>
<script>
var d = document.querySelector("#status");
function init() {
d.style.color = "red";
d.innerHTML = "LOADED";
}
</script>
</body>
The above example checks for page load to happened and then output = LOADED.
Page Resize Event
<body>
<p>pageWidth:<span id="pwidth">Width</span></p>
<p>pageHeight:<span id="pheight">Height</span></p>
<script>
window.onload = resize;
window.onresize = resize;
var d = document.getElementById("pwidth");
var s = document.getElementById("pheight");
function resize(){
d.innerHTML = window.innerWidth;
s.innerHTML = window.innerHeight;
}
</script>
</body>
In the example above, the load page size is given in terms of width and height of the page respectively.
When the page is resized the value of page size also changes.
Scroll Event
<body>
<p>pageHeight:<span id="pheight">Height</span></p>
<script>
var s = document.getElementById("pheight");
s.addEventListener('scroll',scrollPage);
function scrollPage(evt){
s.innerHTML = window.innerHeight;
}
</script>
</body>
In the next article, you will see some keyword events and how to handle them.