jQuery scrollTop()
jQuery scrollTop() is a method that allows you to get or set the vertical scrollbar position in an element. It can be useful for controlling the scroll position of a webpage or manipulating the position of an element within a scrollable container.
Syntax
To get the vertical scrollbar position of an element, you can use the following syntax:
$(selector).scrollTop()
To set the vertical scrollbar position of an element, you can use the following syntax:
$(selector).scrollTop(value)
Use
The scrollTop() method can be used to implement various functionality in your webpage. For example, you can use it to create a "back to top" button that scrolls the user to the top of the page when clicked. You can also use it to control the scroll position of specific elements on your webpage, such as a modal or a dropdown menu.
Example
Here is an example of using scrollTop() to create a "back to top" button:
HTML:
<button id="back-to-top-btn">Back to Top</button>
<div class="content">
<!-- Content goes here -->
</div>
JavaScript:
$(document).ready(function() {
// Hide the button when the page loads
$('#back-to-top-btn').hide();
// Show the button when the user scrolls down 200 pixels
$(window).scroll(function() {
if ($(this).scrollTop() > 200) {
$('#back-to-top-btn').fadeIn();
} else {
$('#back-to-top-btn').fadeOut();
}
});
// Scroll to the top of the page when the button is clicked
$('#back-to-top-btn').click(function() {
$('html, body').animate({
scrollTop: 0
}, 500);
return false;
});
});