tags:

views:

179

answers:

2

I'm using jquery, and need to accomplish a couple things.

1) When someone clicks on a link (or in my case, a div) to display another div, I'd like to add an anchor to the url.

So, if someone clicks on a "Live" link, the 'live' div slides down, and we append #live to the url.

2) If someone visits that page and keeps the #live anchor at the end of the url, then the 'live' div should be visible right away.

I know how to handle the basic part of slideDown() if someone clicks a div. I don't know how to append the hashtag, or make it so that when the page is loaded that hashtag is checked and displays the respective div.

Any help understanding this would be appreciated. Thanks in advance.

+1  A: 

Appening a hash to the URL is as simple as manipulating location.hash, e.g.:

$("a.live").click(function() {
    window.location.hash = 'live'; // not needed if the href is '#live'
});

You can easily test for it's presence and act accordingly based on it's value when the page loads up, e.g.:

$(document).ready(function() {
    var hashVal = window.location.hash.split("#")[1];
    if(hashVal == 'live') {
        $("#live").show();
    }
});
karim79
thanks! exactly what I was looking for.
scatteredbomb
+1  A: 

If you had markup like this:

<a href="#div5" class="toggler">Toggle Div 5</a>
<div id="div5">Content for Div 5</div>

You can do this in jQuery:

$("a.toggler").click(function() {
  $(this.hash).slideToggle();
});

Or use rel or something with a div you click on, like this:

<div rel="#div5" class="toggler">Toggle Div 5</a>
<div id="div5">Content for Div 5</div>

And adjust your jQuery to this:

$("div.toggler").click(function() {
  var hash = $(this).attr("rel");
  $(hash).slideToggle();
  window.location.hash = hash;
});

My recommendation would be to use display:block; on an anchor to do what you want, and leverage the default browser behavior here, it takes care of the hash on click.

No matter which approach above, you can show the one on page load like this:

$(function() {
  if(location.hash != "") {
    $(location.hash + ":hidden").slideDown();
  }
});
Nick Craver