Mihir Ujjainwal
Mihir Ujjainwal

Reputation: 140

javascript window.reload then window.location.href

I want to make a code in which the window reloads and then the location is changed, though i tried window.location.reload(); window.location.href="#id" but it didn't work because when the page will reload, the script won't run.
Actually i want to clear the POST data from the page and then change the location on the same page to an id.

Upvotes: 0

Views: 6770

Answers (2)

Jack
Jack

Reputation: 9388

As others have said, updating the href will trigger a reload, so manually calling reload isn't necessary. If you did want to go that way, it would require a conditional check to prevent infinite reloads you're seeing...say based on some parameter in the url like:

if (window.location.hash === '') {
    window.location.hash = '#id';
    window.location.reload();
} else {
    window.location.hash = '';
}

Just simply updating the hash won't cause a reload, so the following wouldn't work (it would just move to the location)

window.location.href = '#answer-28520707').

However, you could do something like this:

window.location.href = "?_reload" + Date.now() + "#answer-28520707"

The query parameter will cause the browser to refresh the page and the hash will jump to the new location.

If you'd like to test this, try pasting the above in a console or typing this in the address bar:

javascript:void(window.location.href = "?_reload" + Date.now() + "#answer-28520707")

(It should reload the page and scroll to this answer)

Upvotes: 1

TRGWII
TRGWII

Reputation: 648

Just use

window.location.href = "#id";
window.location.reload();

You don't need the reload first, the page will reload just by changing the location.href value.

Upvotes: 1

Related Questions