Created
October 24, 2014 12:01
-
-
Save codekipple/f0bb09924c07b97e5c18 to your computer and use it in GitHub Desktop.
Medium fade on scroll effect
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
dom nodes | |
*/ | |
var $btn; | |
$(document).ready(function () { | |
$btn = $('.js-btn'); | |
fadeFromView({ | |
element: $btn, | |
fadeStart: -200, | |
fadeEnd: -100 | |
}); | |
}); | |
function fadeFromView(options) { | |
/* | |
fadeStart is relative to the top of the element, e.g:- | |
0 = the top of the element | |
-100 = 100px above the top of the element | |
100 = 100px below the top of the element | |
fadeEnd is relative to the bottom of the element, e.g:- | |
0 = the bottom of the element | |
-100 = 100px above the bottom of the element | |
100 = 100px below the bottom of the element | |
*/ | |
var defaults = { | |
element: null, | |
padTop: 0, | |
padBottom: 0, | |
fadeStart: 0, | |
fadeEnd: 0 | |
}; | |
var opt = $.extend({}, defaults, options); | |
var elHeight = opt.element.outerHeight(), | |
elTop = opt.element.offset().top, | |
trackStart = elTop + opt.fadeStart, | |
trackEnd = elTop + elHeight + opt.fadeEnd, | |
trackLength = trackEnd - trackStart; | |
$(document).scrollspy({ | |
onTick: function(element, position, inside, enters, leaves) { | |
var opacity, | |
trackPos; | |
if (position.top < trackStart) { | |
/* | |
scroll position is above the start of the track, element should be fully visible | |
*/ | |
opt.element.css('opacity', 100); | |
} else if (position.top > trackEnd) { | |
/* | |
scroll position is below the end of the track, element should be fully hidden | |
*/ | |
opt.element.css('opacity', 0); | |
} else { | |
/* | |
scroll position is within the track, fade the element based on it's position within the track | |
*/ | |
trackPos = position.top - trackStart; | |
opacity = 1 - (trackPos / trackLength); | |
opt.element.css('opacity', opacity); | |
} | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment