Once I hit a button, I wanted the page to get to its lowest point and then back up. I think some sort of callback would be needed, but I can't define it. I report below the portion of the code concerned.
$(document).ready(function() {
$(".home-button").on('click', function() {
$('html, body').animate({
'scrollTop': $('footer').offset().top
}, 1500);
//then come back
});
});
<html>
<head></head>
<body>
<a >Start</a>
<!-- ... -->
<footer><p>Stop and go back</p></footer>
</body>
<html>
CodePudding user response:
You are right on the callback
part, just add another animate
in the callback
function to scroll back top.
$(document).ready(function() {
$(".home-button").on('click', function() {
$('html, body').animate({
'scrollTop': $('footer').offset().top
}, 1500, 'swing', function() {
$('html, body').animate({
'scrollTop': $('body').offset().top
}, 1500);
});
//then come back
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head></head>
<body>
<a >Start</a>
<!-- ... -->
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<footer>
<p>Stop and go back</p>
</footer>
</body>
<html>
CodePudding user response:
You need to use setTimeout to go back after exactly the animation time!
$(document).ready(function() {
let sameValue = 1500;
$(".home-button").on('click', function() {
$('html, body').animate({
'scrollTop': $('footer').offset().top
}, sameValue );
//then come back
setTimeout(()=>{ $('html, body').animate({
'scrollTop': $('.home-button').offset().top
}, sameValue );},sameValue );
});
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<a >Start</a>
<!-- ... -->
<div style="height:700px;background-color:red;" ></div>
<footer><p>Stop and go back</p></footer>
</body>
<html>