Last active
March 22, 2017 21:16
-
-
Save caiotarifa/e21e6935d7b256b222e71d5ff0c7bdd5 to your computer and use it in GitHub Desktop.
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
var Sticky = function(selector, containerSelector) { | |
var element = document.querySelector(selector), | |
containerElement = document.querySelector(containerSelector), | |
elementTop = parseInt(window.getComputedStyle(element, null).marginTop), | |
stickedClass = 'sticked', | |
grabEndClass = 'grab-end', | |
elementStart, containerElementFinish; | |
if (!canSticky) { | |
return; | |
} | |
setPoints(); | |
window.addEventListener('scroll', function() { | |
if (window.scrollY >= elementStart && window.scrollY < containerElementFinish) { | |
sticky(); | |
} else if (window.scrollY >= containerElementFinish) { | |
grabEnd(); | |
} else { | |
reset(); | |
} | |
}); | |
// Private | |
function offset(element) { | |
var rectangle = element.getBoundingClientRect(); | |
return { | |
top: rectangle.top + document.body.scrollTop, | |
left: rectangle.left + document.body.scrollLeft | |
} | |
} | |
function canSticky() { | |
if (!element && !containerElement) { | |
return false; | |
} | |
if (window.innerHeight <= 710 || window.innerWidth <= 768) { | |
return false; | |
} | |
return true; | |
} | |
// Public | |
function reset() { | |
element.classList.remove(stickedClass, grabEndClass); | |
setPoints(); | |
} | |
function sticky() { | |
element.classList.remove(grabEndClass); | |
element.classList.add(stickedClass); | |
} | |
function grabEnd() { | |
element.classList.remove(stickedClass); | |
element.classList.add(grabEndClass); | |
} | |
function setPoints() { | |
elementStart = offset(element).top - elementTop; | |
containerElementFinish = offset(containerElement).top + containerElement.offsetHeight - element.offsetHeight - elementTop; | |
} | |
return { | |
reset: reset, | |
sticky: sticky, | |
grabEnd: grabEnd, | |
setPoints: setPoints | |
}; | |
}; |
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
.sticked { | |
position: fixed; | |
top: 70px; | |
} | |
.grab-end { | |
position: absolute; | |
bottom: 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment