Created
December 25, 2015 11:41
-
-
Save aTei/8c9a1f5cffce3a4b6f89 to your computer and use it in GitHub Desktop.
Fixer: fixing elements to screen or other elements (depends on jQuery)
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
| doc = $(document) | |
| fixer = -> | |
| doc.trigger('fixer') | |
| $(window).on 'resize', fixer | |
| doc.on 'ready page:load', fixer | |
| fixerAllowed = true | |
| lastTimeout = null | |
| TIME_BETWEEN_STEPS = 30 | |
| FINISH_STEP_DELAY = 70 | |
| doc.on 'scroll', -> | |
| return unless fixerAllowed | |
| fixerAllowed = false | |
| fixer() | |
| setTimeout (-> | |
| fixerAllowed = true | |
| ), TIME_BETWEEN_STEPS | |
| clearTimeout lastTimeout | |
| lastTimeout = setTimeout (-> | |
| fixer() | |
| ), FINISH_STEP_DELAY |
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
| # Usage example | |
| ### global hb ### | |
| doc = $(document) | |
| doc.on 'ready', -> | |
| searchResultsHeader = $('.search-results-header') | |
| return if searchResultsHeader.length < 1 | |
| body = $('body') | |
| OFFSET = 20 | |
| FIXED_CLASS = 'body_search-results-header-fixed' | |
| searchResultsHeaderTop = searchResultsHeader.offset().top - OFFSET | |
| fixer = -> | |
| if doc.scrollTop() > searchResultsHeaderTop | |
| hb.Memo::addClass body, FIXED_CLASS | |
| else | |
| hb.Memo::removeClass body, FIXED_CLASS | |
| doc.on 'fixer', fixer |
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
| class Memo | |
| classCache: {} | |
| cssCache: {} | |
| addClass: (element, name)-> | |
| @toggleClass(element, name, true) | |
| removeClass: (element, name)-> | |
| @toggleClass(element, name, false) | |
| toggleClass: (element, name, toggle)-> | |
| return unless @classCache[name] != !!toggle | |
| element.toggleClass(name, toggle) | |
| @classCache[name] = !!toggle | |
| css: (element, id, name, val)-> | |
| key = id + "/" + name | |
| if @cssCache[key] != val | |
| element.css(name, val) | |
| @cssCache[key] = val | |
| window.hb = {} unless window.hb? | |
| window.hb.Memo = Memo |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment