0

I'm currently having some problems with a hashchange and jQuery mobile conflict, so I'm looking to change the url manually and handle the request myself.
Slight problem though, I'm currently using:

$('#test').click(function() {
    window.location = "/test/#hash"; 
});

Which successfully changes the url as I want it to, but then attempts to load the requested url, I merely want to change the url and NOT prompt a page load. Is this at all possible? Any suggestions would be greatly appreciated!

user1374796
  • 1,544
  • 13
  • 46
  • 76

1 Answers1

1

You can use the pushState method:

window.history.pushState({foo: 'bar'}, 'other page', '/test/#hash');

https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history

Be careful, this functionality is not supported by <= IE9

JAVASCRIPT

$('a').on('click', function(e) {
  var element = $(this),
      element_anchor = element.attr('href'),
      element_title = element.attr('title');
  if (typeof window.history !== 'undefined')
  {
    window.history.pushState({anchor: element_anchor}, element_title, '/test/' + element_anchor);
  }
  e.preventDefault();
});

HTML

<a href="#first_page" title="this is the first page">first page</a>
Paul Rad
  • 4,820
  • 1
  • 22
  • 23
  • this works great, one more thing, is it at all possible to append the `attr` of `#test` to the url? e.g. clicking on `#test` with an `attr` value of `test` will render the url like so: `/test/#hash`? – user1374796 Sep 29 '13 at 12:44
  • updated response with an example ;-) – Paul Rad Sep 29 '13 at 12:52