scrollTop
PropertyYou can use the jQuery animate()
method in combination with the scrollTop
property to scroll to the top of the web page smoothly with an animation.
Let's try out the following example to understand how it basically works:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery scrollTop Animation</title>
<style>
.scroll-top{
position: fixed;
bottom: 10px;
right: 10px;
z-index: 99;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function(){
$(".scroll-top").click(function() {
$("html, body").animate({
scrollTop: 0
}, "slow");
return false;
});
});
</script>
</head>
<body>
<button type="button" class="scroll-top">Go to Top</button>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit...</p>
</body>
</html>
However, if you simply want to scroll to the top of the page without any animation or jQuery you can use the native JavaScript window.scrollTo(x-coord, y-coord)
method, like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Scroll to Top</title>
<style>
.scroll-top{
position: fixed;
bottom: 10px;
right: 10px;
z-index: 99;
}
</style>
<script>
function goToTop(){
window.scrollTo(0, 0);
}
</script>
</head>
<body>
<button type="button" class="scroll-top" onclick="goToTop();">Go to Top</button>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit...</p>
</body>
</html>
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
How to find the number of words in a string in PHP
Use the PHP str_word_count() f...How to remove first character from a string in jQuery
Use the JavaScript substring() method...Laravel URL Validation Rule Example
Sometimes you may want to validate url i...Laravel 8 - Excel and CSV Import Export to Database using maatwebsite/excel with Example.
Excel file import-export to the database...How to Connect MySQL Database in Python?
In this article, I will share with you h...