Skip to content

Instantly share code, notes, and snippets.

@jbuncle
Created May 19, 2016 12:54
Show Gist options
  • Save jbuncle/8c4b1b47d3e428d8210ece85ebb31286 to your computer and use it in GitHub Desktop.
Save jbuncle/8c4b1b47d3e428d8210ece85ebb31286 to your computer and use it in GitHub Desktop.
Adds class to bookmark/local links when the linked element is in view.
/*!
* Adds class to bookmark/local links when the linked element is in view.
*
* Requires https://gist.github.com/jbuncle/6f6185e88be875b2585e736a422c3f15 for detecting when element is in view.
*
* Copyright 2016 James Buncle
*
* Released under the MIT license.
* http://jquery.org/license
*
*/
(function ($) {
$.fn.scrollHighlight = function (className) {
return this.filter('[href^="#"]').each(function () {
var $link = $(this);
var target = $link.attr('href').replace(/("|'|&|:|\.|\[|\]|,|\(|\)|\/|\?)/g, "\\$1");
var $for = $(target);
$(window).scroll(function () {
if ($for.inViewport()) {
$link.addClass(className);
} else {
$link.removeClass(className);
}
});
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment