change the element when it reaches the top

0

I'm trying to make this code to change the element when it reaches the top, the element will stay fixed until the next one hits the top.

HTML

  <p>
  elemento A  
  </p>

 <p>
  elemento B  
 </p>

 <p>
  elemento C  
 </p>

JS

function scroll() {
    (window).scroll(function() {
        if ($(window).scrollTop() > elementPosition.top) {
            $('p').css('position', 'fixed').css('top', '0');

        } else {
            $('p').css('position', 'static');


        }
    });
}
    
asked by anonymous 16.10.2017 / 21:59

1 answer

0

You can loop through the elements by checking which is at the top and apply fixed , and those that are not, apply static :

curr_fixed = 0;
$(window).on("scroll", function(){
	els = $("p");
    janela_scroll = $(window).scrollTop();
	$.each(els, function(i,v){
		if( ($(this).offset().top)-janela_scroll <= $(this).outerHeight() ){
			curr_fixed = i;
			$(this).css({
				"position":"fixed",
				"top":"0px"
			});
			
			$.each(els, function(i,v){
				if(i != curr_fixed){
					$(this).css({
						"position":"static",
						"top":"0px"
					});
				}
			});
		}
	});
});
html, body{ margin: 0; padding: 0; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
	elemento A  
</p>
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<p>
	elemento B  
</p>
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<p>
	elemento C  
</p>
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
    
17.10.2017 / 00:31