Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop default hashtag behavior with jquery

Tags:

jquery

url

anchor

I'm using the following code to append a hashtag to the end of a url. That way someone can copy that url and take them back to that page, with certain divs visable.

$("a.live").click(function() {
    window.location.hash = 'live'; 
    $("#live).slideDown();
});

In this example I have a div called 'live', that would slideDown when a link is clicked, and '#live' added to the url. Then I have code that checks the hash tags when the page is loaded to show the proper divs.

My problem is, how do I prevent the browser from jumping to the 'live' div once it's called? I don't want the page to scroll down to the div, just want it opened and the hashtag appended so a person could copy it and come back to that page with that div showing.

Any tips?

Thank you!

like image 975
Andelas Avatar asked May 17 '10 20:05

Andelas


2 Answers

Try this:

$("a.live").click(function() {
    window.location.hash = 'live'; 
    $("#live").slideDown();
    return false; // this will prevent default action
});
like image 111
sasa Avatar answered Nov 11 '22 19:11

sasa


It depends. If you want to prevent it when the anchor is clicked, use this:

$("a.live").click(function(e) {
    e.preventDefault(); // Prevents browsers default action
    window.location.hash = 'live'; 
    $("#live").slideDown();
});

If you want to prevent it from scrolling to the hash when the page is loaded, I'm not sure how you would prevent that.

like image 8
steve_c Avatar answered Nov 11 '22 19:11

steve_c