Skip to content

Instantly share code, notes, and snippets.

@wgkoro
Created October 24, 2012 11:43
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save wgkoro/3945642 to your computer and use it in GitHub Desktop.
Make scroll button at bottom of the page.
/*
Author : wg_koro
Version : 1.0
Update : 2012/10/24
License : MIT
- How to use -
Set this script in header.That's all! :)
(Example) <script type='text/javascript' src='xxxx/spscroll.js' charset='utf-8'></script>.
*/
(function(){
// Do nothing if user agent is PC.
if(! navigator.userAgent.toLowerCase().match('(iphone|android)')) return;
var config = {
startFrom : 250,
string : 'ページトップ', // String in button
opacity : 0.5,
scrollRate : 80
};
var button = document.createElement('nav');
var showFlg = false;
var setButtonView = function(){
setInterval(function(){
var position = getPosition();
if (position.y > config.startFrom){
if(! showFlg) showButton();
}
else{
if(showFlg) hideButton();
}
}, 100);
};
var showButton = function(){
showFlg = true;
var current = 0;
var showTimer = setInterval(function(){
if(current >= config.opacity) clearInterval(showTimer);
current += 0.1;
button.style.opacity = current;
}, 25);
};
var hideButton = function(){
showFlg = false;
var current = config.opacity;
var hideTimer = setInterval(function(){
if(current <= 0) clearInterval(hideTimer);
current -= 0.1;
button.style.opacity = current;
}, 25);
};
var getPosition = function(){
var pos = {};
pos.y = document.documentElement.scrollTop || document.body.scrollTop;
pos.x = document.documentElement.scrollLeft || document.body.scrollLeft;
return pos;
};
var scrollToTop = function(){
var position = getPosition();
var scrollTimer = setInterval(function(){
if(position.y <= 0) clearInterval(scrollTimer);
var scrollTo = position.y - config.scrollRate;
window.scroll(position.x, scrollTo);
position = getPosition();
}, 10);
};
var setButton = function(){
var style = 'position:fixed;';
style += 'bottom:2px;right:2px;';
style += 'width:100px;height:20px;';
style += 'background-color:#000;';
style += 'padding:6px 5px 5px 5px;';
style += 'text-align:center;';
style += 'color:#fff;';
style += 'font-size:90%;';
style += 'z-index:999;';
style += 'opacity:0;';
style += '-webkit-border-radius:5px;';
style += 'border-radius:5px;';
button.setAttribute('style', style);
document.body.appendChild(button);
button.innerHTML = config.string;
button.addEventListener('click', scrollToTop);
setButtonView();
};
window.addEventListener('load', setButton);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment