Last Updated on May 5, 2021 by Roshan Parihar
In this tutorial, learn how to fix div on top when scrolling using jQuery. It makes the div sticky to the top of the screen on scroll. The short answer is: use the CSS property position:fixed
to fix the div and jQuery scrollTop()
method to set the scrolling position.
How to Fix Div on Top When Scrolling Using jQuery
To make the div fix on top when scrolling, you have to initially hide the div using the CSS display:none
property. After that, you have to use the jQuery scrollTop()
method. Inside that method, you have to use the show()
and hide()
as given below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
<!DOCTYPE html> <html lang="en"> <head> <title>jQuery Fix Div on Top on Scrolling</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script> $(window).scroll(function() { if ($(this).scrollTop()>100) { $('.myDiv').show(1000); } else { $('.myDiv').hide(1000); } }); </script> <style> body{ height: 1000px; } div{ background: #34d234; border: 1px solid #000; padding: 10px; height:40px; position:fixed; display:none; top:0; width:100%; z-index:100; } </style> </head> <body> <p><strong>Scrolldown the screen to see the effect.</strong></p> <div class="myDiv"> </div> </body> </html> |
The above example uses the CSS position: fixed
and the top:0
to make the <div>
element fixed at the top position. The value 100 in with the scrollTop()
method shows that it check the position if greater than the specified value. After that position, it displays the fixed div element at the top of the screen.
FAQS on How to Fix Div on Top When Scrolling Using jQuery
1. How to Make Div Fixed After Scrolling?
Answer: You have to apply the CSS position:fixed
and top:0
to the <div>
element. To make div appear fixed after scrolling, use the scrollTop()
method. Set the position value to the method to make div fixed after scrolling.
2. How to Make Div Fixed to the Bottom of the Screen on Scrolling?
Answer: You can use the CSS position:fixed
property with bottom:0
to the <div>
element. To make div appear fixed at the bottom on scrolling, you have to use the scrollTop()
method.
3. How Do I Make Div Always Stays on Top?
Answer: To make the div always stays on top, you can use the CSS property position:fixed
and top:0
to the <div>
element. These two CSS properties make the div element fixed at the top position of the screen.
You May Also Like to Read