简体   繁体   中英

Showing elements based on window height with a scroll event

I'm wanting to show elements based on the location of the scroll and window.

The technique I'm wanting to achieve is something similar to a infinite loading

Current fiddle: http://jsfiddle.net/fxJ7s/14/

$('.item:gt(5)').hide();

function loadMore() {

    var items = $(".item").length;
    var shown = 6;

    shown = $('.item:visible').length + 3;
    console.log(shown);

    if (shown < items) {
        $('.item:lt(' + shown + ')').show();
    }

    $(window).bind('scroll', bindScroll);
}

function bindScroll() {
    if ($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
        $(window).unbind('scroll');
        loadMore();
    }
}

$(window).scroll(bindScroll);

Right now, I'm hiding every element except for the first 6. Then when a user scrolls down the next 3 will be shown. I can see in the console that they are becoming visible, however I don't want them to all appear at once. Ideally 3 would appear and then another 3 as the height of the window is scrolled.

It seems that the height of the window isn't updating after the first 3 are made visible?

This is something that is working, but with a click function instead. http://jsfiddle.net/nFd7C/327/

Any pointers or help is appreciated. :)

I have answered a question similar to this before. In my experience the best way forward, in this instance, is to run a function when a user scrolls to the end of the page that loops through the items that are visible and then unhides a further 9 items. This function is then repeated when a user scrolls to the end of the page each time.

I have put together a quick example of the logic behind my answer. I see that you are using a CSS framework. For the sake of this example I have used a CSS rule with an !important declaration in order to override your framework. I would not suggest using !important but instead employ a separate stylesheet of custom styles that overrides the frameworks rules as and when required.

DEMO http://jsfiddle.net/fxJ7s/15/

$(".item").addClass("noshow");
var contentNumber = 0;

function reveal() {
    var constraintNumber = contentNumber + 9;
    for (i = contentNumber; i < constraintNumber; i++) {
        $('.item').eq(contentNumber).removeClass("noshow");
        contentNumber++;
    }
}

//Window scroll function
$(window).scroll(function () {
    if ($(window).scrollTop() == $(document).height() - $(window).height()) {
        reveal();
    }
});
reveal();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM