How do i launch a function when web page loads?

I need to load a function when you first visit the web page only once, so basically i got a menu that has onclick and when you click on for example about it hides the rest of the css and only shows the css with id=“page_2” etc. So basically i need id=“page_1” to load when the web page loads.

Here’s the javascript:


<script>
  for (var i = 1; i <= 5; i++) {
    if (i === 1)
      document.getElementById('page_' + i).style.display = "block"
    else
      document.getElementById('page_' + i).style.display = "none"
  }

  function loadPage(varcontent) {
    var var1 = "";
    var1 = varcontent;
    var num = var1.slice(-1);

    document.getElementById(var1).style.display = "block";
    for (var i = 1; i <= 5; i++) {
      if (i == num)
        document.getElementById('page_' + i).style.display = "block"
      else
        document.getElementById('page_' + i).style.display = "none"
    }
        loadPage(page_1); <!-- Here is my attempt -->
  }
</script>

You’re trying to load the function inside itself. If you need to run it and pass in variables, then you should do it outside the function.

If this function just needs to be ran once, then you could just use a Self Executing Anonymous Function.

(function(varcontent) { 
    var var1 = "";
    var1 = varcontent;
    var num = var1.slice(-1);
    
    document.getElementById(var1).style.display = "block";
    
    for (var i = 1; i <= 5; i++) {
      if (i == num)
        document.getElementById('page_' + i).style.display = "block"
      else
        document.getElementById('page_' + i).style.display = "none"
    }
})(page_1); 

As long as you put this at the bottom of your page, just before the last </body> tag, you shouldn’t have any issues. Trying to put either attempts between the <head> tags will result in a function that will not work correctly.

Didn’t work.

Managed to solve my issue i did:
<body onload="loadPage('page_1')">

That is not very helpful to anybody trying to solve your problem :slight_smile:

My JavaScript knowledge is very limited.

My last attempt at JavaScript was solved by opening the browser debugger and clearing the red flags. Have you tried the debugger and are there any red flags appearing?

Edit
I was a bit too slow typing on my mobile :frowning:

1 Like

Issue is solved now with an onload in the body tag :slight_smile:

1 Like

More than likely you have your code in the header, which I addressed at the bottom of my post.

You also changed page_1 from a variable to a string.

Glad you got it working.

You should never jumble the JavaScript with the HTML.

JavaScript goes just before the </body> tag where most can just run straight away. If a delay for other files to load is still required then you use addEventListener to listen for the ‘load’ event on the window.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.