Change hash without rebooting 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 just causes the div to disappear depending on when you click, but I want the hash tag of the page to change when you click, so people can copy and add bookmarks. At the moment, this effectively reloads the page when the hash tag changes.

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

+51
jquery window.location reload hash fragment-identifier
Dec 21 '09 at 9:14
source share
3 answers

It 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 http://jsbin.com/edicu for a demo with almost identical code

+79
Dec 21 '09 at 11:47
source share

You can try to catch the onload event. And stop propagation depends 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 I can’t say if this will work

+4
Dec 21 '09 at 9:33
source share

The accepted answer did not work for me, as my page bounced slightly by clicking on my scroll animation.

I decided to update the entire URL using window.history.replaceState rather than using the window.location.hash method. Thus, bypassing the hashChange event triggered by the browser.

 // Only fire when URL has anchor $('a[href*="#"]:not([href="#"])').on('click', function(event) { // Prevent default anchor handling (which causes the page-jumping) event.preventDefault(); if ( location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname ) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); if ( target.length ) { // Smooth scrolling to anchor $('html, body').animate({ scrollTop: target.offset().top }, 1000); // Update URL window.history.replaceState("", document.title, window.location.href.replace(location.hash, "") + this.hash); } } }); 
0
Mar 29 '17 at 23:59 on
source share



All Articles