Reputation: 683
I'm currently trying to make a button which will take the user back to the top of the page, but animated. Making the page scroll back up to the top when the button is clicked. I did a search on here and found this..
And I have attempted to make a JSfiddle of this using the following...
CSS
html {
margin:0;
padding:0;
height:2000px;
}
body {
height:2000px;
}
#blue-box {
position:fixed;
width:100px;
height:70px;
margin-left:0px;
margin-top:50px;
background-color:blue;
}
#blue-box h1{
font-family:Constantia;
font-size:20px;
text-align:center;
margin-top:5px;
color:#FFFFFF;
}
HTML
<div id="blue-box">
<h1>Back To Top</h1>
</div>
JavaScript
$(document).ready(function() {
var away = false;
$('#blue-box').click(function() {
$("html, body").animate({scrollTop: 0}, 500);
});
Unfortunately, this doesn't seem to work and I'm wondering whether I have missed something out or done something obviously wrong?
Upvotes: 0
Views: 10685
Reputation: 311
This is also a slight variation where the button only fades in once you start scrolling down the page and disappears once you return to the top of the page http://jsfiddle.net/b4M66/
jQuery:
$(function() {
$(window).scroll(function() {
if($(this).scrollTop() != 0) {
$('#toTop').fadeIn();
} else {
$('#toTop').fadeOut();
}
});
$('#toTop').click(function() {
$('body,html').animate({scrollTop:0},800);
});
});
CSS:
#toTop { position: fixed; bottom: 50px; right: 30px; width: 84px; background-color: #CCC; cursor: pointer; display: none; }
HTML:
<div id="toTop">Back to Top</div>
Upvotes: 0
Reputation: 262939
You're missing a });
at the end of your script. Adding it solves your problem:
$(document).ready(function() {
var away = false;
$('#blue-box').click(function() {
$("html, body").animate({scrollTop: 0}, 500);
});
}); // <-- Here.
That's a good example of why indenting your code properly is important. It makes this kind of error far more difficult to miss.
Upvotes: 5