2

Possible Duplicate:
Handle URL anchor change event in js
How to do awesome refreshless page changes like GitHub

In my app I'm using this very simple code to add a hashtag:

         <a href='#test'> <input type='submit'></input>

I would like the page to refresh when I press the back button. For now, it only goes from www.mysite.com/#test to www.mysite.com.

I saw different questions on this topic, but I didn't find how to accomplish that.

Thank you for your help.

Community
  • 1
  • 1
Marcolac
  • 901
  • 4
  • 14
  • 27
  • It sounds like you are trying to change basic behavior of a browser. "Refresh" refreshes the page and "back" goes back. That should stay that way. – Ulises Jan 05 '13 at 20:37
  • 2
    If you want to use `fragment identifiers` (**NOT** called Hash Tags) for navigating your site, then you should leverage the [History API](https://developer.mozilla.org/en-US/docs/DOM/Manipulating_the_browser_history) – Ohgodwhy Jan 05 '13 at 20:39
  • Check this question: http://stackoverflow.com/questions/2161906/handle-url-anchor-change-event-in-js – Frank van Puffelen Jan 05 '13 at 20:41
  • HTML does not allow input elements inside a elements. – Quentin Jan 05 '13 at 20:42

2 Answers2

3

A simple way would be to wait for the hash change event to occur and then react to it. Whenever the # changes, the function will be called and if the hash is empty, the page is going to be reloaded.

window.addEventListener('hashchange', function() {
  console.log(window.location.hash);

  if('' === window.location.hash) {
    console.log('reload');
    //window.location.reload();
  }
});

http://jsfiddle.net/kcKLE/1/

I'd suggest using a library like jQuery for the event-binding stuff, since addEventListener doesn't work in any browser. (Hello IE) https://developer.mozilla.org/en/docs/DOM/element.addEventListener

If you need something fancier, there is also a history api around. https://developer.mozilla.org/en-US/docs/DOM/Manipulating_the_browser_history

Robin Drexler
  • 4,307
  • 3
  • 25
  • 28
0

I just found how to accomplish that. I'm using the onhashchange functionality. Here is my code:

    document.body.setAttribute("onhashchange", "update()");
         function update() {
            if('' === window.location.hash) {
                 window.location.reload();
          }

      };

So when I press the back button the hash disappears and the page reloads.

Thank you for the hints everybody.

Marcolac
  • 901
  • 4
  • 14
  • 27