views:

1410

answers:

2

Hello,

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?

Thanks

Dave.

+1  A: 

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

James Wiseman
for one, you'd need to pass the local variable "event" into "StopEvent"
Rob Fonseca-Ensor
Oops. Thanks edited accordingly.
James Wiseman
Thanks for this will give it a whirl.
daveredfern
I don't think it's a good idea to do it this way, but the StopEvent function is really nice. +1
naugtur
+3  A: 

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

jitter
Hello, Yes it does work but when the page is scrolling it jumps to the div when the hash link is changed.
daveredfern
Check changed code which fixes that. If you don't want that to happen you just have to switch the last two lines. The original order was yours and I kept it that way because I thought that's what you wanted
jitter
Thanks :) Did the job great.
daveredfern