Question

I'm trying to update data in the info box (outlined in red) when the user scrolls the content area (outlined in blue) and the next item is nearly at the green line. How could this be done?

Website http://puu.sh/3sKnx.PNG

Tank you for any help!

Edit: If it makes a difference: The big headbar on top and the info box are fixed <divs> with a high z-index

Was it helpful?

Solution

It's very difficult to give a great answer with just a picture and nothing to work with, but I'd imagine something similar to below would work.

$("#top-heute").on("scroll", function() {
    var fromTop = $(this).scrollTop(); // Find the scrolled position
    var viewing = Math.round(fromTop / 100) // Assuming your entries are 100 pixels heigh
    // Call some function which sets the info
    setInfo(viewing); // If you had all results in an array e.g.
    setInfo($(".entries", this).slice(viewing - 1)); // Sending across the relevant 'entry'
});

Edit Based on your requirement to allow each of the rows to be of a variable width, I've produced a JSFiddle which demonstrates one way you could approach this problem.

The Javascript is the most important thing to look at:

// Trigger this each time we scroll our div
$("#scroll").on("scroll", function() {
    // Keep track the last row
    var last = $(); 
    // Loop through each row
    $(".row", this).each(function() {
        // If it's scrolled position is above or greater than 10px (margin) we've gone too far, break
        if($(this).position().top >= 10) return;
        last = $(this); // Update the last element otherwise
    });
    var update = $("#updated");
    // Update our info box based on the last element's 'data' attributes
    $(".face", update).html("<img src='" + last.attr("data-img") + "' alt='Profile Picture' />");
    $(".name", update).html(last.attr("data-name"));
    $(".about span", update).html(last.attr("data-last"));
});
// Run the scroll function when we load
$("#scroll").scroll();

Hope this helps. FYI this kind of thing is known as a ScrollSpy.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top