Skip to content Skip to sidebar Skip to footer

Location.reload(), Javascript,html

I'm having a problem always when I try to use the following code in a button in my HTML file. onClick=window.location.reload(); mapGenerator(); The page reloads but the javascript

Solution 1:

location.reload() will immediately reload the page and prevent any following code to execute.

You can, however, create a function that executes your method after the page has (re)loaded:

window.onload = function() {
    mapGenerator();
};

This method will run every time the page has fully loaded. To only run the code after you have reloaded the page using location.reload(), you could create a method that handles the click by setting a cookie and then reloading the page.

functionhandleClick() {
    document.cookie="reload=true";
    location.reload();
}

This would require you to change your onClick value to onClick="handleClick();". Now, whenever the page loads, you can check whether the cookie has been set. Your window.onload function now changes to this:

window.onload = function() {
    if(document.cookie.indexOf("reload") >= 0) {
        mapGenerator();
    }
}

Checking if a cookie exists - answer by Michael Berkowski

After the reload it's up to you whether you want to unset the cookie — if you don't, the page will run the function mapGenerator on every page load until the cookie expires.

If you need more help with cookies, check out W3Schools' tutorial.

Solution 2:

As per your description mentioned above two actions are to be taken on click. As the first action reloads the page the second action is lost. If you want any action to be taken on load of the page, mention the same on onload event of the page.

Post a Comment for "Location.reload(), Javascript,html"