Last active
August 13, 2017 09:54
-
-
Save Loiree/cd715ecd76071b8bed2ccb361eddf368 to your computer and use it in GitHub Desktop.
Scroll-to-anchor: прокрутка к якорю
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
<div data-scroll="elemIdOrJustNumber">HOME</div> |
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 ScrollToAnchor = (function() { | |
return { | |
init: function() { | |
this.cache(); | |
this.settings(); | |
this.bindEvents(); | |
}, | |
cache: function() { | |
this.buts = document.querySelectorAll("[data-scroll]"); | |
}, | |
settings: function() { | |
this.timing = "ease-in-out"; | |
this.duration = 800; | |
}, | |
bindEvents: function() { | |
var self = this; | |
var i; | |
for (i=0; i < this.buts.length; i++) { | |
this.buts[i].addEventListener("click", function() { | |
self.scroll(this); | |
}); | |
} | |
}, | |
scroll: function(but) { | |
var self = this; | |
var endPoint; | |
var dataScroll = but.getAttribute("data-scroll"); | |
// если dataScroll не число, то достаем координаты элемента | |
if (isNaN(parseInt(dataScroll))) { | |
var endElem = document.getElementById(dataScroll); | |
if (!endElem) return; | |
var box = endElem.getBoundingClientRect(); | |
endPoint = box.top + pageYOffset; | |
} else { | |
endPoint = parseInt(dataScroll); | |
} | |
var start = window.pageYOffset; | |
var pos; | |
var fn = function(progress) { | |
pos = start * (1 - progress) + progress * endPoint; | |
window.scrollTo(0, pos); | |
}; | |
AnimHandler.init(fn, this.duration, this.timing); | |
} | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment