Robert
Robert

Reputation: 27

Prevent page redirect when using hash tag

Is there any way to redirect a page to a specific hash but prevent the redirect if the page is reloaded with a hash already present? Preferably with javascript?

For example:

typing in www.mysite.com redirects to ---> www.mysite.com/index.html#news

then the user clicks a link that navigates to a new location further down the same page to: www.mysite.com/index.html#articles

what I want is to prevent the redirect upon refresh so that if the user refreshes the page they remain on #articles rather than being redirected back up to #news.

essentially the only purpose for the redirect is to take people to #news only if the url is typed in without a hash(#).

Upvotes: 0

Views: 2444

Answers (2)

maerics
maerics

Reputation: 156652

You can inspect the window.location.hash property and set the location href based on its value. For example:

<script type="text/javascript">
  // Redirect to "#news" if there is no hash in the URL.
  if (window.location.hash == '') {
    window.location.href = 'http://www.mysite.com/index.html#news';
  }
</script>

Incidentally, it seems that you can use either window.location or document.location which appear to do the same thing. It is unclear which is the preferred target (window or document).

Upvotes: 1

Jamie Treworgy
Jamie Treworgy

Reputation: 24344

Anchor redirects are a client-only construct. The server has absolutely no knowledge of the fact that someone clicked "#articles" -- and the URL does not change when they do so, so refreshing will always land you on the same URL that got you there.

The solution is to rewrite the URL when they click on an anchor link. You can change it by assigning to window.location.href. So add a click handler to any hash anchor, and change the URL to incorporate the new in-page anchor tag.

Upvotes: 0

Related Questions