change the element when it reaches the top

Asked

Viewed 40 times

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 reaches 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');


        }
    });
}

1 answer

0


It is possible to loop the elements by checking which one is at the top and apply fixed, and those who 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 />

Browser other questions tagged

You are not signed in. Login or sign up in order to post.