0

I am working on a Bootstrap, jQuery project where I'm applying scrolling animations and functionality to the HTML.

When I am loading an HTML document, I want to know if the user navigated to "this" document with an ID or resource specified at the end of the URL, like so:

http://domain.example/page#section

Essentially, I want to execute jQuery code relatively to whether somebody navigates to the document having specified no ID at the end of the URL, or having specified one. I would assume that if this is possible, it would be done in $(document.ready()).

I find this pretty easy to do if I'm navigating to a resource on the same page, but in this instance where I'm navigating from a different page, I'm stuck and I would really appreciate a response whether this is possible or not.

kalehmann
  • 4,821
  • 6
  • 26
  • 36

1 Answers1

0

While this is a relatively similar question to that of this, of which this answer describes a simple answer of checking whether or not a hash fragment exists:

if(window.location.hash) {
  // Fragment exists
} else {
  // Fragment doesn't exist
}

I realise, you may well want to check for different hash fragments, so I've added upon the answer to get this:

var hash = window.location.hash.replace('#','');
if(hash == "section") {
    // Fragment exists and is equal to section 
} else {
    // Fragment doesn't exist
}

This checks for a hash fragment in the URL, if it exists and is equal to #section the if statement returns true.

Studocwho
  • 2,404
  • 3
  • 23
  • 29