Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change hash without reload in jQuery

I have the following code:

$('ul.questions li a').click(function(event) {     $('.tab').hide();     $($(this).attr('href')).fadeIn('slow');     event.preventDefault();     window.location.hash = $(this).attr('href'); }); 

This simply fades a div in based on when you click but I want the page URL hash tag to change when you click so people can copy and bookmark it. At the moment this effectively reloads the page when the hash tag is change.

Is it possible to change the hash tag and not reload the page to prevent the jumping effect?

like image 736
daveredfern Avatar asked Dec 21 '09 09:12

daveredfern


2 Answers

This works for me

$('ul.questions li a').click(function(event) {     event.preventDefault();     $('.tab').hide();     window.location.hash = this.hash;     $($(this).attr('href')).fadeIn('slow'); }); 

Check here http://jsbin.com/edicu for a demo with almost identical code

like image 191
jitter Avatar answered Oct 05 '22 03:10

jitter


You could try catching the onload event. And stopping the propagation dependent on some flag.

var changeHash = false;  $('ul.questions li a').click(function(event) {     var $this = $(this)     $('.tab').hide();  //you can improve the speed of this selector.     $($this.attr('href')).fadeIn('slow');     StopEvent(event);  //notice I've changed this     changeHash = true;     window.location.hash = $this.attr('href'); });  $(window).onload(function(event){     if (changeHash){         changeHash = false;         StopEvent(event);     } }  function StopEvent(event){     event.preventDefault();     event.stopPropagation();     if ($.browser.msie) {         event.originalEvent.keyCode = 0;         event.originalEvent.cancelBubble = true;         event.originalEvent.returnValue = false;     } } 

Not tested, so can't say if it would work

like image 44
James Wiseman Avatar answered Oct 05 '22 05:10

James Wiseman