Highlighted Anchors

by Mark Penner

HTML

<script src="https://raw.github.com/jquery/jquery-color/master/jquery.color.js"></script>
<a href="#hello">hello</a>
<a name="hello">world</a>

JavaScript

// http://stackoverflow.com/q/487073/65387
// https://github.com/jquery/jquery-color

function isScrolledIntoView(elem) {
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom) && (elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

$('a[href]').filter(function() {
    return $(this).attr('href')[0] == '#';
}).click(function() {
    var name = $(this).attr('href').substring(1); // TODO: escape this
    var elem = $("[name='" + name + "']").eq(0);
    elem.css({
        'backgroundColor': '#FDFEB3'
    }).delay(1000).animate({
        backgroundColor: 'transparent'
    }, 1500);
    return !isScrolledIntoView(elem);
});