Skip to content

Instantly share code, notes, and snippets.

@johanbrook
Created November 25, 2014 23:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johanbrook/4aabe9d429fd8bc9d3d4 to your computer and use it in GitHub Desktop.
Save johanbrook/4aabe9d429fd8bc9d3d4 to your computer and use it in GitHub Desktop.
jQuery plugin for drawing an SVG line while scrolling.
/*
jQuery plugin for drawing a svg line as you scroll.
@author Johan Brook, for Lookback (2014).
Options:
startAt: The reference point to start calculating from. Expects a selector.
speed: at which speed the line should draw.
offset: the offset of which the reference point should be.
*/
$.fn.scrollStroke = function(options) {
var defaults = {
startAt: document,
speed: 400,
offset: 0
}
options = $.extend({}, defaults, options)
var hideLine = function(line) {
line.style.strokeDasharray = [ 0, line.getTotalLength()].join(' ')
}
var drawLine = function(line, reference, speed) {
var pathLength = line.getTotalLength(),
percentDone = reference / speed,
length = percentDone * pathLength
if(percentDone > 1) return
line.style.strokeDasharray = [ length, pathLength ].join(' ')
}
return this.each(function() {
var line = this
$(window).on('scroll', function() {
var startAt = $(options.startAt).offset().top,
reference = $(window).scrollTop() - startAt + options.offset
// Hide line completely
if(reference < 0) {
hideLine(line)
return
}
drawLine(line, reference, options.speed)
})
})
}
@GianCastle
Copy link

Hello. Can you tell me how to implement this plugin, please?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment