Floating, fixed ad block, banner on scrolling screen in JS and jQuery.
Floating banner on scrolling screen in jQuery.
This jQuery algorithm determines the initial height from the block to the top of the screen. Operator offset().top is used.
Then, when scrolling the screen, we compare the number of scrolled pixels on the screen. Operator scrollTop() is used.
And if the initial coordinate of the block is less, then add the class .fixed to the element.
This class makes the block position: fixed.
<STYLE> .fixed-div { width: 200px; height: 180px; text-align: center; background: #FFA500; padding: 10px 0; } .fixed { position: fixed; z-index: 9999; top: 0; } </STYLE> <div class="fixed-div"> Code menu<BR>or<BR>baner... </div> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <SCRIPT> $(function(){ $nav = $(".fixed-div"); $window = $(window); $h = $nav.offset().top; $window.scroll(function(){ if ($window.scrollTop() > $h) { $nav.addClass("fixed"); } else { $nav.removeClass("fixed"); } }); }); </SCRIPT>
Floating banner on scrolling screen in JS.
This Java Script algorithm determines the initial height from the block to the top of the screen. Operator offsetTop is used.
Then, when scrolling the screen window.onscroll, we compare the number of scrolled pixels on the screen. Operator JS window.pageYOffset is used.
And if the initial coordinate of the block is less then css property top:20px; position:fixed ;.
Otherwise block have property of the position:static;.
<STYLE> #fixblock { width: 200px; background: aqua; padding: 10px 0; text-align: center; } </STYLE> <div id="fixblock"> Code menu<BR>or<BR>baner... </div> <script type="text/javascript"> var block = document.getElementById("fixblock"); var topPos = block.offsetTop; window.onscroll = function() { var newcss = (topPos < window.pageYOffset) ? "top:20px; position:fixed;" : "position:static;"; block.setAttribute( "style", newcss ); } </script>