Prince
Prince

Reputation: 1192

Add an #hashtag in the URL by using window.location

I am having this page example.com/index.php with different sections. Each section can be accessed by the following link.

  1. first section : example.com/index.php#first
  2. second section : example.com/index.php#second

When the user gets to the page example.com/index.php, he is supposed to be directed to the first section so I used this code:

<script> window.location = "#first"; </script>

Any time I try to access example.com/index.php#second I am directed to the first section (example.com/index.php#first), instead of being directed to the second section.

Kindly help me solve the issue. Sorry I am not a native english speaker.

Upvotes: 0

Views: 1670

Answers (1)

demux
demux

Reputation: 4654

I think in this case it's a matter of using a simple conditional:

if(!window.location.hash) {
    window.location.hash = '#first'
}

Upvotes: 4

Related Questions