Last active
February 21, 2016 11:51
-
-
Save stephancom/8300b0cef07f2a0177ad to your computer and use it in GitHub Desktop.
coffeescript text carousel
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
# by: _ _ | |
# __| |_ ___ _ __| |_ __ _ _ _ __ ___ _ __ | |
# (_-< _/ -_) '_ \ ' \/ _` | ' \ _/ _/ _ \ ' \ | |
# /__/\__\___| .__/_||_\__,_|_||_(_)__\___/_|_|_| | |
# |_| stephan@stephan.com | |
# Unobtrusive txtRotate | |
# http://codepen.io/stephancom/details/pgXypp/ | |
# applies to all elements with data-rotate | |
# expects | |
# data-rotate: an array of strings | |
# data-period: duration | |
# optional | |
# data-wait: don't trigger immediately | |
# data-complete: selector for element(s) to be triggered on complete | |
$ -> | |
class TxtRotate | |
constructor: (@el) -> | |
@el = $(@el) | |
@toRotate = @el.data('rotate') | |
return unless @toRotate? | |
@period = @el.data('period') | |
@loopNum = 0 | |
@txt = '' | |
@isDeleting = false | |
@el.on 'txtRotate:start', => | |
console.log "=> starting rotate:", @toRotate | |
@tick() | |
@el.trigger('txtRotate:start') unless @el.data('wait')? | |
tick: -> | |
i = @loopNum % @toRotate.length | |
fullTxt = @toRotate[i] | |
if @isDeleting | |
@txt = fullTxt.substring(0, @txt.length - 1) | |
else | |
@txt = fullTxt.substring(0, @txt.length + 1) | |
@el.html('<span class="wrap">' + @txt + '</span>') | |
delta = 100 | |
if @isDeleting | |
delta /= 2 | |
if @txt == '' | |
@isDeleting = false | |
@loopNum++ | |
delta = 500 | |
else if @txt == fullTxt and @loopNum < 1 | |
delta = @period | |
@isDeleting = true | |
if @loopNum == @toRotate.length - 1 and @txt == fullTxt | |
$(@el.data('complete')).trigger('txtRotate:start') unless @done | |
@done = true | |
setTimeout (=> @tick() ), delta unless @done | |
# INJECT CSS --> for mobilefirst | |
css = document.createElement('style') | |
css.type = 'text/css' | |
css.innerHTML = '.txt-rotate > .wrap { border-right: 0.08em solid #666 }' | |
document.body.appendChild css | |
console.log('==> setting up txtRotate') | |
$('[data-rotate]').each (i, el) -> new TxtRotate el | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment