Reputation: 49
So, i have a little arrow in my page:
<a href="#" class="scrollToTop"><img src="images/arrow_up.png"></a>
I wanna make it invisible when the page is at the top and then, as the user scrolls down, to make it visible so the user can click to go back to the top of the page. This Javascript doesn't seem to be working:
$(document).ready(function(){
//Check to see if the window is top if not then display button
$(window).scroll(function(){
if ($(this).scrollTop() > 100) {
$('.scrollToTop').fadeIn();
} else {
$('.scrollToTop').fadeOut();
}
});
//Click event to scroll to top
$('.scrollToTop').click(function(){
$('html, body').animate({scrollTop : 0},800);
return false;
});
});
I also have this css (which is working):
.scrollToTop{
padding: 1em;
color: #444;
position: fixed;
right: 0;
bottom: 0;
-webkit-transition: -webkit-transform .3s ease-in-out;
-ms-transition: -ms-transform .3s ease-in-out;
transition: transform .3s ease-in-out;
z-index: 1;
}
.scrollToTop:hover{
-webkit-transform:rotate(360deg);
-moz-transform:rotate(360deg);
-o-transform:rotate(360deg);
}
I'd apreciate some help! :)
Upvotes: 0
Views: 924
Reputation: 178
Not sure if your exact issue was this, but copying your code into a JS fiddle revealed that if the page was less than the window height, the arrow would always show.
A fix for this was to include a default display:none
and then check window height on scroll. Checking it every time would allow the page to grow and shrink and still allow the arrow to only display when needed.
A working example can be seen at this JSFiddle.
$(document).ready(function(){
//Check to see if the window is top if not then display button
$(window).scroll(function(){
ShowScroll();
});
//Click event to scroll to top
$('.scrollToTop').click(function(){
$('html, body').animate({scrollTop : 0},800);
return false;
});
function ShowScroll() {
if (window.innerHeight < $("body").height())
{
var elem = $(".scrollToTop");
if (elem.css("display") == "none") elem.css("display","inline");
if ($(this).scrollTop() > 100) {
$('.scrollToTop').fadeIn();
} else {
$('.scrollToTop').fadeOut();
}
} else {
$(".scrollToTop").css("display","none")
}
}
Upvotes: 1