Created
September 15, 2016 19:13
-
-
Save sergeh/05f0157548ed87e3120a0dcffb421523 to your computer and use it in GitHub Desktop.
jQuery Decode effect
This file contains hidden or 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
body { font-family: monospace; } | |
.code { color: red; } |
This file contains hidden or 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
<span id="sometext">Hello, world</span> |
This file contains hidden or 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
jQuery.fn.decodeEffect = (function ($) { | |
var defaultOptions = { | |
duration: 3000, | |
stepsPerGlyph: 10, | |
codeGlyphs: "ABCDEFGHIJKLMNOPQRSTUWVXYZ1234567890", | |
className: "code" | |
}; | |
// get a random string from the given set, | |
// or from the 33 - 125 ASCII range | |
function randomString(set, length) { | |
var string = "", i, glyph; | |
for(i = 0 ; i < length ; i++) { | |
glyph = Math.random() * set.length; | |
string += set[glyph | 0]; | |
} | |
return string; | |
} | |
// this function starts the animation. Basically a closure | |
// over the relevant vars. It creates a new separate span | |
// for the code text, and a stepper function that performs | |
// the animation itself | |
function animate(element, options) { | |
var text = element.text(), | |
span = $("<span/>").addClass(options.className).insertAfter(element), | |
interval = options.duration / (text.length * options.stepsPerGlyph), | |
step = 0, | |
length = 0, | |
stepper = function () { | |
if(++step % options.stepsPerGlyph === 0) { | |
length++; | |
element.text(text.slice(0, length)); | |
} | |
if(length <= text.length) { | |
span.text(randomString(options.codeGlyphs, text.length - length)); | |
setTimeout(stepper, interval); | |
} else { | |
span.remove(); | |
} | |
}; | |
element.text(""); | |
stepper(); | |
} | |
// Basic jQuery plugin pattern | |
return function (options) { | |
options = $.extend({}, defaultOptions, (options || {})); | |
return this.each(function () { | |
animate($(this), options); | |
}); | |
}; | |
}(jQuery)); | |
$("#sometext").decodeEffect(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment