How can I create Wikipedia's footnote highlighting solely with jQuery

I copied Wikipedia's superscript markup verbatim:

<sup class="reference" id="cite_ref-1">
    <a href="#cite_note-1">
        <span>[</span>1<span>]</span>
    </a>
</sup>

And used the following jQuery:

$(".reference > a").click(function() {
    var href = $(this).attr("href");
    var $el = $(href);

    $(".ref-highlight").removeClass("ref-highlight");
    $el.addClass("ref-highlight");
});

The key is grabbing the href off of the link that was clicked, and then using that to select the element and apply the highlight class.

Also, you don't need to scroll the page down programmatically, because the browser handles this for you automatically.

Here's a complete working example: http://jsfiddle.net/andrewwhitaker/dkWJm/2/


Update: I noticed in your comment below you'd like to animate the scrolling, here's how you would do that:

$(".reference > a").click(function(event) {
    event.preventDefault();
    var href = $(this).attr("href");
    var $el = $(href);

    $(".ref-highlight").removeClass("ref-highlight");
    $el.addClass("ref-highlight");
    $("html, body").animate({"scrollTop": $el.offset().top}, 3000);
});

Notes:

  • We're canceling the default action of the link in this case (using event.preventDefault()), which would be to jump to the element with the id matching the clicked link's href.
  • Using animate to smoothly scroll the html element down to the appropriate position, which is determined using offset() on the target element.
  • The duration argument (I specified 3000) is what you would tweak to lengthen/shorten the duration of the scroll.

Here's an example of this: http://jsfiddle.net/andrewwhitaker/dkWJm/4/ (Updated to work in IE8/Chrome/FF 3)