Using Jquery to toggle on and off items based distance to top

I am creating a site in which there are a number of fixed background images that you scroll past. Associated with each fixed background is an image slider (or text) that is hidden until the title is clicked on. These items are all fixed positioned.

I was able to make this work by using z-index to place items in order top to bottom/first to last and then have each disappear in turn using:

Read More
$(document).scroll(function() {
    $('#porttitle').toggle($(this).scrollTop() < 225);
});

However, I am unable to use this because the length pixel distance down on the page changes based on the screen size. I am pretty new to Jquery but wanted to try to use .offset .top to have the item disappear not based on the pixel length to the top of the page but instead when an element appears on the screen. This is what I have so far but it isn’t seeming to work.

$(document).scroll(function() {
    $('#porttitle').toggle($(this).scrollTop() < $(‘article.post-100’).offset().top);
});

Here is the link to the site: http://s416809079.onlinehome.us (not final location – just developing)

Any thoughts?

Thanks!

Related posts

Leave a Reply

1 comment

  1. I think this may work for you, read the comments on the code for a line by line explanation.

    Working Example

    $(window).scroll(function () { // When the user scrolls
        $('div').each(function () { // check each div
            if ($(window).scrollTop() < $(this).offset().top) { // if the window has been scrolled beyond the top of the div
                $(this).css('opacity', '1'); //change the opacity to 1
            } else { // if not
                $(this).css('opacity', '0'); // change the opacity to 0
            }
        });
    });
    

    I’m conditionally changing the opacity rather than using toggle because:

    …jQuery does not support getting the offset coordinates of hidden
    elements or accounting for borders, margins, or padding set on the
    body element.

    While it is possible to get the coordinates of elements with
    visibility:hidden set, display:none is excluded from the rendering
    tree and thus has a position that is undefined.

    Related documentation:
    .offset()
    .each()
    .scroll()
    .scrollTop()