skip to Main Content

I have a javascript file like below which changes the innerHtml value of a header.

window.addEventListener("onload", function (e) {
    console.log("Hit Javascript file");
    if (this.document.getElementById('cardHeader')) {
        document.getElementById('cardHeader').innerHTML = "Card Header Text";
    }
});

The changes are noticeable for half a second and then it reverts back to its original value. I tried using defer incase the page wasn’t fully loaded. I also tried positioning the script tag inside the header, body and outside the body.

Inside my layout html this is where i’ve added the script.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <base href="~/" />
 
    <link href='https://fonts.googleapis.com/css?family=Inter' rel='stylesheet'>
    <script type="text/javascript"
            src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

    <component type="typeof(HeadOutlet)" render-mode="ServerPrerendered" />
</head>


<body>
    @RenderBody()

    <script src="https://mysitehere.azurewebsites.net/login-script.js" defer></script>
</body>

</html>

2

Answers


  1. The problem here is that onload is an incorrect parameter to be used with window.addEventListener:
    https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event
    Try

    window.addEventListener("load", function (e) {
        console.log("Hit Javascript file");
        if (document.getElementById('cardHeader')) {
            document.getElementById('cardHeader').innerHTML = "Card Header Text";
        }
    });
    

    instead.
    Alternatively,

    window.onload = (event) => {
        console.log("Hit Javascript file");
        if (document.getElementById('cardHeader')) {
            document.getElementById('cardHeader').innerHTML = "Card Header Text";
        }
    };
    
    Login or Signup to reply.
  2. In the first parameter of addEventListener(), "onload" should just be "load":

    window.addEventListener("load", function (e) {
        console.log("Hit Javascript file");
        if (document.getElementById('cardHeader')) {
            document.getElementById('cardHeader').innerHTML = "Card Header Text";
        }
    }, false);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search