0

I'm trying to get certain <div>s to show up when the url has a certain hash. So far, it works when I am navigating from a different page but doesn't work when I click from the same page.

Example: If I am on the page1 and click to go to /page2#hash1 then div1 linked to hash1 will show up on page2 (all the <div>'s are initially hidden). But if the url is currently /page2#hash1 and I want to jump to #hash2 on the same page, the url will change to /page2#hash2 but div2 will not show up and div1 won't go away.

Here is the code I am trying to use:

if (window.location.href.indexOf('#hash1') > -1){
    $('.div1').slideToggle();
} else if(window.location.href.indexOf('#hash2') > -1 ) {
    $('.div2').slideToggle();
}
scniro
  • 16,844
  • 8
  • 62
  • 106
  • 2
    On which event are you running this code? The window onload event is not fired when the hash changes IIRC. You might need to use https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers.onhashchange to listen for hash change events. – HaukurHaf Jan 11 '15 at 21:29

1 Answers1

3

Use the onhashchange event to trigger your function

window.onhashchange  = function(){
  if (window.location.href.indexOf('#hash1') > -1){
            $('.div1').slideToggle();
        }
        else if(window.location.href.indexOf('#hash2') > -1 ) {
            $('.div2').slideToggle();
        }

}

JSFiddle care of @HaukurHaf

Justice Erolin
  • 2,869
  • 20
  • 19