It is necessary that the block sticks to the top during the roll. How to implement it? If you can, give an example, please. I think that it is necessary to do a class through the scrool function and add a class when a certain height is reached, but it cannot be implemented.
3 answers
Example
$(window).scroll(function() { if ($(window).scrollTop() >= 100) { $('nav').addClass('fixed'); } else { $('nav').removeClass('fixed'); } }); body { padding: 0; margin: 0 } header { background: #ccc; height: 100px; } section { min-height: 1000px; } nav { position: absolute; left: 0; top: 100px; background: #00f; width: 100%; height: 50px; z-index: 99; } nav.fixed { position: fixed; top: 0; background: #f00; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <header>header</header> <nav>Блок, который прилипает</nav> <section>Контент</section> - Thank! Exactly what is needed. And how to make the block reach a certain place, for example, a footer, and not go further? - Alexander
- in google for the phrase scrollBottom look for - soledar10
- Googled, but how to apply to your case - I do not understand. Could you tell me please? - Alexander
- @ Alexander jsfiddle.net/soledar10/bfb0v5vm - soledar10
- Thank you, but unfortunately not exactly what you need. My block initially has absolute positioning, and should stick when skrule. + he sticks to the screen, and i need him to stay within the parent. - Alexander
- We hang up the handler on scrol event
- Check the state of scrolling
- If the scroll is more than necessary, then add a class in which the block is given
position:fixed
window.onscroll = function() {//событие скрола var scrolled = window.pageYOffset || document.documentElement.scrollTop; if(scrolled >= 200) document.getElementById("top-block").classList.add("fixed-top"); } #top-block{ position:relative; } #top-block.fixed-top{ position:fixed; top:0; left:0; } <div id="top-block">content</div> To solve this problem, I wrote a jQuery plugin that uses the position: fixed; property position: fixed; to the element when the page scrolls below its position. The modifier class is also added to the element ( __fixed by default), thanks to which you can customize the appearance of a fixed element.
When this is in place of the target element is an empty element stub, which prevents the deformation of the page structure.
Using:
$('.js-fixed').fixed(options); With the help of settings you can set your own class-modifier and indent from the element on which it is necessary to "fix" . Read more about this on GitHub .
However, if you need a solution on vanilla javascript, you will have to put some effort into rewriting the plugin. But I think the source code should help you with this.
- And with the help of this plugin, you can make the sidebar, for example, scrolled only to the footer and no further? - Alexander
- @ Alexander this behavior was not taken into account in it, unfortunately - Konstantin Basharkevich