views:

54

answers:

1

I have a 2-frame HTML page:

  • FrameA contains a list of links to various pages, or anchors within pages
  • FrameB displays the individual pages.

Some of the pages contain slideDown sections, with trigger text - i.e. clicking this text shows/hides the slideDown section below it.

The parent element of the trigger element also contains an anchor, for example:

<li class="expandable">
  <p><a name="myanchor3"></a>Trigger text</p>
  <div class="slideDownSection">
       ...
  </div>
</li>

I want to detect whenever an anchor is requested in the URL used to load the page into FrameB. If there is an anchor ref, I want to check whether the anchor falls within an "expandable" element and, if it is, I do a slideDown on the element below to display it.

I can do this easily enough by putting some Javascript inside a $(document).ready(function(){ ... }); in the page that gets loaded. This checks the location.hash value and processes it if one's found. However, this only works when the page gets loaded into FrameB.

If a page is already loaded into FrameB and I click a link in FrameA that points to another anchor within the same page, I can't capture that event. The page position changes to display the anchor at, or near, the top of the page - without reloading the page.

My question is:
What event handler can I use in the page displayed in FrameB to detect that an anchor on that page has been requested via a link clicked in FrameA?

Note: The content of FrameA is auto-generated, so I can't use an onClick event for the page in FrameA, I can only work within the pages that get displayed in FrameB.

+1  A: 

IE8 supports the hashchange event that you can listen for. For all other browsers, you have to poll the value of location.hash using setInterval():

var lastHash = null;
function checkHash() {
  if (window.location.hash != lastHash) {
    lastHash = window.location.hash;

    // Do your hash stuff
  }
}

setInterval(checkHash, 100);

http://stackoverflow.com/questions/680785/on-window-location-hash-change is a very similar question.

Annabelle
Thanks. The functionality I'm adding is nice-to-have stuff, not must-have stuff, so I'm going to go with the hashchange event like you suggest and users with IE8 (or FF3.6 when that comes out) will get this, but folks on other browsers just won't get the automated slidedowns - I can live with that. Thanks.
Alistair Christie