Question

The page has a container div which holds multiple content divs. Each content div has a named anchor. Only one of the content divs is displayed at a time:

Example:

<style>
  .lurk { display: none; }
</style>
<div class="container">
  <div id="c1">
    <a name="#c1">One</a> is the loneliest number.
  </div>
  <div id="c2" class="lurk">
    <a name="#c2">Two</a> is company.
  </div>
  <div id="c3" class="lurk">
    <a name="#c3">Three</a> is a crowd.
  </div>
</div>
<script>
// ... something that adds and removes the lurk class from the content divs
</script>

The desired behavior is that if someone requests the page using a valid named anchor in the URL, the JavaScript / JQuery will see it and set the various display properties appropriately so that the content corresponding to the named anchor is visible.

  1. Is the requesting URL available to JQuery?
  2. Is checking for named anchors in the URL usually done early in $(document).ready?()
  3. Is this hard to get right in a cross-browser way?
  4. Is there a library routine for extracting the anchor from an URL, or does everybody roll their own regular expression?
Was it helpful?

Solution

You can use location.hash to retrieve the anchor from the URL. This will work across browsers and will work in $(document).ready.

For example:

$("div.container > div").removeClass("lurk");
if (location.hash)
    $("#" + location.hash).addClass("lurk");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top