This blog is all bout sticky div on scroll javascript with an example, in this blog, you will get how to stick a div when scrolling the browser to the top of the browser.
In the below example you will see the search bar
of the HTML page is sticked at top after scroll top.
Set-1
1 2 3 4 5 6 7 8 9 10 11 | <div id="boxHere"></div> <div class="input-group" id = "boxThis"> <input type="text" class="form-control" placeholder="Search Blog.."> <span class="input-group-btn"> <button class="btn btn-default" type="button"> <span class="glyphicon glyphicon-search"></span> </button> </span> </div> </div> |
Add the extra DIV <div id="boxHere"></div>
and add id = "boxThis"
this code in which div has to stick at the top.
Set-2
Add a small line of CSS below
1 2 3 4 5 6 7 8 9 10 11 12 13 | <style> #boxThis.box { margin-top: 0; position: fixed; top: 0; width: 300px; z-index: 9999; -webkit-border-radius: 0 0 10px 10px; border-radius: 0 0 10px 10px; } </style> |
Set-3
Add a small piece JS of code in the Footer section
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 | <script> function boxtothetop() { var windowTop = $(window) .scrollTop(); var top = $('#boxHere') .offset() .top; if(windowTop > top) { $('#boxThis') .addClass('box'); $('#boxHere') .height($('#boxThis') .outerHeight()); } else { $('#boxThis') .removeClass('box'); $('#boxHere') .height(0); } } $(function() { $(window) .scroll(boxtothetop); boxtothetop(); }); </script> |
Now it will work.
Still, if you want this code, Please click here to download it.