Site menus are usually at the top. After reading a long document, there is the inconvenience of having to scroll for a while to go back to the menu. There are many places to provide a link to the top to get rid of this inconvenience. Creating a simple link will instantly move you to the top, but jQuery's scrollTop () makes it easy to create an effect that slurries up to the top.
Create a link in your HTML document.
<a href="#" class="top">Top</a>
Make sure that the position does not change when you scroll, and that you cannot see it after taking a proper position.
a.top {
position: fixed;
left: 50%;
bottom: 50px;
display: none;
}
Scroll down to some extent so you can see the link when you go down.
$( window ).scroll( function() {
if ( $( this ).scrollTop() > 200 ) {
$( '.top' ).fadeIn();
} else {
$( '.top' ).fadeOut();
}
} );
When clicked, it gives an animation effect so that it will be thrilled up.
$( '.top' ).click( function() {
$( 'html, body' ).animate( { scrollTop : 0 }, 400 );
return false;
} );
Here's the full code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery</title>
<style>
div {
margin: auto;
width: 500px;
height: 2000px;
border: 1px solid #bcbcbc;
}
a.top {
position: fixed;
left: 50%;
bottom: 50px;
display: none;
}
</style>
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$( document ).ready( function() {
$( window ).scroll( function() {
if ( $( this ).scrollTop() > 200 ) {
$( '.top' ).fadeIn();
} else {
$( '.top' ).fadeOut();
}
} );
$( '.top' ).click( function() {
$( 'html, body' ).animate( { scrollTop : 0 }, 400 );
return false;
} );
} );
</script>
</head>
<body>
<div></div>
<a href="#" class="top">Top</a>
</body>
</html>
When you go down to the bottom of the document, you'll see a link called Top in the middle of the bottom of your web browser, and clicking on that link will slowly move you up to the top.
'jQuery' 카테고리의 다른 글
[jQuery] Method / .clone ()-Method to clone selected element (0) | 2022.07.27 |
---|---|
[jQuery] Select all checkboxes, create deselect all (0) | 2022.07.25 |
[jQuery] Get the horizontal size of the selected element --width, innerWidth, outerWidth (0) | 2022.07.25 |
[jQuery] How to move object to desired position using jquery (0) | 2022.07.22 |
[jQuery] change image with jquery (0) | 2022.07.22 |