How to Add a Back-to-Top Button to WordPress
wordpress back to top buttonadd scroll to top wordpresswordpress custom css javascriptimprove wordpress user experiencewordpress footer.php code
Published·Modified·
If your blog homepage displays a lot of content, or if article pages are quite long, adding a back-to-top feature to WordPress is undoubtedly very practical. It helps improve user experience, so friends who haven't added it yet should give it a try.
1. Add the following code to the style.css file in your theme directory. Of course, you can modify it according to your own style:
/* Back to top style */
#gotop{
width:38px;
height:36px;
position:fixed;
bottom:25px;
right:10px;
top:auto;
display:block;
cursor:pointer;
background: url(myimages/top.gif) no-repeat
}
*html #gotop{
position:absolute;
bottom:auto; top:expression(eval(document.documentElement.scrollTop+document.documentElement.clientHeight-this.offsetHeight-(parseInt(this.currentStyle.marginTop,10)||0)-(parseInt(this.currentStyle.marginBottom,10)||0)));
}
/* Back to top style end */
2. Add the following code to the footer.php file in your theme directory to call the function:
<!-- Back to top -->
<div style="display: none;" id="gotop"></div>
<script type='text/javascript'>
backTop=function (btnId){
var btn=document.getElementById(btnId);
var d=document.documentElement;
var b=document.body;
window.onscroll=set;
btn.onclick=function (){
btn.style.display="none";
window.onscroll=null;
this.timer=setInterval(function(){
d.scrollTop-=Math.ceil((d.scrollTop+b.scrollTop)*0.1);
b.scrollTop-=Math.ceil((d.scrollTop+b.scrollTop)*0.1);
if((d.scrollTop+b.scrollTop)==0) clearInterval(btn.timer,window.onscroll=set);
},10);
};
function set(){btn.style.display=(d.scrollTop+b.scrollTop>100)?'block':"none"}
};
backTop('gotop');
</script>
<!-- Back to top END -->
3. Place the following image in the myimages folder within your theme directory, and name it top.gif. Alternatively, you can modify the path and name in line 11 of Step 1.
