Change div content based on scroll position

I hope for some help using this code from another Stack Exchange post. Below is javascript:

$(window).on("scroll resize", function(){ var pos=$('#date').offset(); $('.post').each(function(){ if(pos.top >= $(this).offset().top && pos.top <= $(this).next().offset().top) { $('#date').html($(this).html()); //or any other way you want to get the date return; //break the loop } }); }); $(document).ready(function(){ $(window).trigger('scroll'); // init the value }); 

I implemented it on my own website here: http://peterwoyzbun.com/newscroll/scroll.html . When the scroll position reaches a certain point, the information in the field changes. At the moment, the changing content comes directly from the div ".post". That is, when the user scrolls to the specified ".post", a fixed gray box loads what is in the ".post".

What I would like to do is display a gray window with a description of what the user is currently seeing. Therefore, when the user reaches the div “content1”, a text description “content1” is displayed in the gray box. Maybe when "content1" is reached, the div "description1" becomes hidden in the gray box?

Any help would be greatly appreciated. Thanks!

+4
source share
1 answer

Add a hidden element inside each section containing the description, for example:

 <div id="content1"> <p class="description" style="display: none;">content1 description</p> .... </div> 

then in javascript get the description of the corresponding section as follows:

 if(pos.top >= $(this).offset().top && pos.top <= $(this).next().offset().top) { $('#date').html($(this).find('.description').text()); return; } 

Jsfiddle

+2
source

All Articles