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.
That is not very helpful to anybody trying to solve your problem
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?
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.