0

I have a json array of instructor data that feeds into a template and generates a "card" for each instructor. Each instructor contains a named anchor and I want to be able to link to the various generated anchors from an external page. i.e. instructors.htm#MrsTaylorGreen

It seems that by the time the cards have a chance to generate, all the browser's jump-to-anchor behavior is done.

I'm considering this bit of jQuery derived from here

// page load, draw instructor cards then...
// scroll to the named anchor if there is one
var anchor = document.location.href.split("#")[1];
if($("#" + anchor).length)
    $('html, body').animate({
        scrollTop: $("#" + anchor).offset().top
    }, 2000);

Is this necessary? Or is there a more efficient alternative to link to dynamic anchors?

Community
  • 1
  • 1
Shanimal
  • 10,987
  • 7
  • 58
  • 71

1 Answers1

2

Use this instead, to get the hash (for your anchor):

var anchor = window.location.hash;

and then:

if ($(anchor).length > 0)
    $('html, body').animate({
    scrollTop: $(anchor).offset().top
}, 2000);

The way you get the hash document.location.href.split("#")[1]; can (and will) produce errors if there is no hash in the URL; because the array (from the split) will have only one element in that case.

Onur Yıldırım
  • 27,841
  • 11
  • 78
  • 96
  • stupid me... of course. I remember something I was writing throwing an "index out of bounds" error, however I wasn't getting that in any of my current browsers (Opera, Webkit, and Mozilla) so I figured it must have been PHP or something and just moved on. And how silly that I forgot about all the other parsings (that are usually not what I need) I think I need to relax my mind and get away from this machine. Anyway +1 For the pro-tip, thank you! – Shanimal Feb 08 '13 at 03:19