Skip to content
Advertisements

JavaScript Window Event

We will see the use of JavaScript window event. The following section contains all the events.

AttributeValueDescription
onafterprintscriptCodes to run after the web page is loaded.
onbeforeprintscriptCodes that will run before the document is written.
onbeforeunloadscriptCodes to run when closing a document
onerrorscriptCodes to run if there are errors in the document.
onhashchangescriptCodes to run when the url( # ) structure of the document changes.
onloadscriptCodes that will run when the document is finished loading.
onmessagescriptFires when the message event occurs i.e. when user sends a cross-document message or a message is sent from a worker with postMessage() method.
onofflinescriptCodes that will run if the web page is not opened due to internet connection.
ononlinescriptcodes that will work when the web page is connected to the internet again.
onpagehidescriptCodes that will run when switching to another web page.
onpageshowscriptcodes that will run after the web page is loaded (works after the onload feature)
onpopstatescriptFires when changes are made to the active history.
onresizescriptTarayıcı penceresi boyutları değiştirildiğinde çalışacak kodlar.
onstoragescriptScript to be run when a Web Storage area is updated
onunloadscriptCodes to run when closing a document.

onafterprint Event Attribute

The JavaScript onafterprint feature works if a dialog box closes when a page is opened or refreshed. The onafterprint feature is generally not used. used with onbeforeprint.

Syntax:

<element onafterprint=”event”>

  • event: The part that will work in printing.

Example:

<body onafterprint="myEvent()">

onbeforeprint Event Attribute

The JavaScript onbeforeprint property is the exact opposite of the onafterprint property. onafterprint was working after printing. The onbeforeprint feature works before printing. The onbeforeprint feature that I mentioned in the section is used with the onbeforeprint.

<element onafterprint=”event”>

  • event: The part that will work in printing.
<body onbeforeprint="myEvent()">

onbeforeunload Event Attribute

The onbeforeunload property of the JavaScript works when you are prompted to remove the document. This is generally used in today’s websites. As he leaves a page, he asks whether he really wants to leave. It does this with the confirmation dialog box.
The checkboxes are different in different browsers:

Typically, the messages are: “Are you sure you want to leave this page?”.

onbeforeunload Examples :

Example 1:  HTML:

<body onbeforeunload="return message()">

    <script>
        function message() {
            return "Are you sure you want to leave this page?";
        }
    </script>

</body>

Example 2: JavaScript

        window.onbeforeunload = function message() {
            return "Are you sure you want to leave this page?";
        }

Example 3:  addEventListener() method

    window.addEventListener("beforeunload", function(event) {
        event.returnValue = "Are you sure you want to leave this page?";
    });

onerror Event

The JavaScript onerror feature works when something goes wrong while the page loads or when an error occurs.

onerror  Examples :

Example 1: in html

<body onerror="myError()" >

Example 2: in javascript

        element.onerror = function () {
            /// codes .......
        }

Example 3: addEventListener

        document.getElementById("myImg").addEventListener("error", myFunction);

        function myFunction() {
            document.getElementById("demo").innerHTML = "The image could not be loaded.";
        }

onhashchange Event

The JavaScript onhashchange feature works when the anchor portion of the current page’s URL is modified. The anchor is called the ‘#’ symbol that starts with the ‘#’. For example, “https: //truecodes.org#example”. The anchor part here is “#example”.

onhashchange Examples

Example 1

onhashchange example 1
<body onhashchange="changeHash">

    <button onclick="change()">CHANGE</button>
    <p id="result"></p>

    <script>

        function change() {
            location.hash = "example";
            var url = location.hash;
            document.getElementById("result").innerHTML = url;
        }

        function changeHash() {
            alert("hash part changed.")
        }

    </script>
</body>

Example 2

onhashchange example 2
<body>

    <button onclick="change()">CHANGE</button>
    <p id="result"></p>

    <script>
        function change() {
            location.hash = "example";
            var url = location.hash;
            document.getElementById("result").innerHTML = url;
        }

        document.getElementsByTagName("BODY")[0].onhashchange = function() {
            changeHash();
        };

        function changeHash() {
            alert("hash part changed.")
        }

        
    </script>
</body>

Example 3

onhashchange example 3
<body>

    <button onclick="change()">CHANGE</button>
    <p id="result"></p>

    <script>

        window.onhashchange = changeHash;

        function change() {
            location.hash = "example";
            var url = location.hash;
            document.getElementById("result").innerHTML = url;
        }

        function changeHash() {
            alert("hash part changed.")
        }

    </script>
</body>

Example 4

onhashchange example 4
<body>

    <button onclick="change()">CHANGE</button>
    <p id="result"></p>

    <script>

        addEventListener("hashchange", changeHash)

        function change() {
            location.hash = "example";
            var url = location.hash;
            document.getElementById("result").innerHTML = url;
        }

        function changeHash() {
            alert("hash part changed.")
        }

    </script>
</body>

onload Event

The JavaScript onload feature works when the web page’s images, videos, and articles are fully loaded. So, shortly after the web page is loaded, it works. Usually used in the element. For example, this feature allows you to design different web pages in different browsers.

Examples:

Example 1

onload example 1
<body onload="onloadFunction()">

    <script>

        function onloadFunction() {
            alert("The onloadFunction property is running.")
        }

    </script>
</body>

Example 2

onload example 2
        window.onload = onloadFunction();

        function onloadFunction() {
            alert("The onloadFunction property is running.")
        }

Example 3

onload example 3
<body>

    <iframe class="website" src="https://truecodes.org" width="400px" height="500px"></iframe>

    <script>

        document.querySelector(".website").addEventListener("load", onFunction);

        function onFunction() {
            alert("The onloadFunction property is running")
        }


    </script>
</body>

Example 4

onload example 4
<body>
    <iframe id="website" src="googlse.des" width="100px" height="100px"></iframe>
    <div id="image"></div>

    <script>

        var img = document.getElementById("image"),
            web = document.getElementById("website");
        
        img.addEventListener("load", webPageError())

        function webPageError() {
            if (navigator.cookieEnabled == true) {
                img.innerHTML = "<img src='https://kodoloji.com/wp-content/uploads/1-qdFdhbR00beEaIKDI_WDCw.gif'>"
            }
            else {
            }
        }

    </script>
</body>

onpageshow Event

The JavaScript onpageshow property occurs when the page is loaded. But not immediately. onload occurs immediately after the page is loaded. onpageshow takes place after the onload feature (another difference is the time to load in the cache)

onpageshow  Examples

Example 1

onpageshow example 1
<body onpageshow="onPageShowFunction()">

  <h2>truecodes.org</h2>
  <p>onpageshow experiment</p>

    <script>
    
        function onPageShowFunction() {
            alert("onpageshow worked successfully")
        }

    </script>
</body>

Example 2

onpageshow example 2
        window.addEventListener("pageshow", onPageShow);

        function onPageShow() {
            alert("onpageshow worked successfully")
        }

Example 3

onpageshow example 3
<body onload="onloadFunction()" onpageshow="onpageFunction()">

    <h2>onload VS onpageshow</h2>

    <script>

        function onloadFunction() {
            alert("onloadFunction")
        }

        function onpageFunction() {
            alert("onpageFunction")
        }


    </script>
</body>

onresize Event

The JavaScript onresize feature works when the browser size changes. You can run this feature if you play with the size of the browser. There are websites that still use this feature, even if they are not used in today’s websites.

But it is possible to use it as follows; for example you have a web page. You made reponsive settings on this web page. But still, after a certain size, your web page’s image is deteriorating. This feature can be used to alert the user to that size.

onresize Examples

Example 1

onresize example 1
<body onresize="resize()">
    <p>Change the size of the page</p>
    <p id="result"></p>
    
    <script>

        function resize() {
            let res = document.getElementById("result");
            let w = window.outerWidth;
            let h = window.outerHeight;
            let txt = "width=" + w + ", height=" + h;
            res.innerHTML = txt;
        }


    </script>
</body>

Example 2

onresize example 2
<body>
    <p>Change the size of the page</p>
    <p id="result"></p>
    
    <script>

        addEventListener("resize", resize);

        function resize() {
            let res = document.getElementById("result");
            let w = window.outerWidth;
            let h = window.outerHeight;
            let txt = "width=" + w + ", height=" + h;
            res.innerHTML = txt;
        }


    </script>
</body>

Example 3

onresize example 3
<body>

    <p>Height: <span id="height"></span></p>
    <p>Width: <span id="width"></span></p>

    <script>



        function resize() {
            const width = document.getElementById("height"),
                  height = document.getElementById("width");
            width.innerHTML = window.innerWidth;
            height.innerHTML = window.innerHeight;
        }
        window.onresize = resize;



    </script>
</body>

Example 4

onresize example 4
<body>

    <p>You have changed the size of the screen <span id="times"></span> times.</p>

    <script>

        addEventListener("resize", resize);
        let a = 0;
        function resize() {
            let times = document.getElementById("times");
            a += 1;
            times.innerHTML = a;
            
        }

    </script>
</body>

onunload Event 

The JavaScript Onload property is the opposite of the onload property. onload works after the page is loaded. it runs after the page closes. For example; a forum is full but wrongly close the page. With this feature, you can store the database of the places you filled in the forum. And when you reopen the web page, you can continue where you left off. It uses a lot of large web pages.

For example, if you mistakenly close the page while writing an article in wordpress. Drafts are written to the database as a draft. This way, you can continue your operation from where you left off.

Let me give you another example. For example; You are on the web page of the bank. You will load a certain amount of money. Suddenly the internet went off and the page was closed. So what happens in this case? I flew money? No. (There are similar features. In general, banks provide data security with little use of javascript). Money remained in the database. If you open the web page again, you can continue your transaction from where you left off.

onunload  Examples

Example 1

onunload example
<body onunload="myFunction()">

<h1>Welcome to my Home Page</h1>

<p>Close this window or press F5 to reload the page.</p>
<p><strong>Note:</strong> Due to different browser settings, this event may not always work as expected.</p>

<script>
function myFunction() {
  alert("Thank you for visiting W3Schools!");
}
</script>

</body>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: