Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery to change content in div based on scroll position

Tags:

jquery

blogs

I am building a blog page in Wordpress and adding a sidebar that points to the current post. I'd like to fill that sidebar with the date of the current post using jQuery. It's only an idea so I don't have any code. But it would function like this:

enter image description here

As you scroll down the page the date (or other info) would change based on which div you were next to. It also has to work in a blog setting meaning each div can potentially be a different height.

Any thoughts?

like image 487
user1161032 Avatar asked Feb 22 '12 00:02

user1161032


1 Answers

I do not know where you want to get the date from, so, just an example.. http://jsfiddle.net/Nsubt/

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

$(document).ready(function(){
  $(window).trigger('scroll'); // init the value
});
​

Div on the right could have a fixed position or you can update its absolute position in the block working with scroll and resize events.

like image 153
Cheery Avatar answered Oct 13 '22 00:10

Cheery