简体   繁体   中英

Toggle div visibility according to scroll position and content height

I'm trying to achieve having simple sharing buttons on the side of a post, which are only visible if the post is within the view. So they are hidden if the user is scrolling above or below that post.

jQuery waypoint it my current weapon of choice. My approach consists of:

// first hiding the div
$('.post-sharing-side').hide();

// fading it in as soon as the headline reaches the top of the viewspace (that feels right in my use case)
$('.entry-title').waypoint(function(direction) {
    $('.post-sharing-side').fadeIn();
});

// fading it out again as soon as the upcoming div reaches the bottom of the viewspace
MISSING

I'm having trouble figuring out the last part: fading it out again. Ideally it should also work when scrolling up again. Any ideas would be highly appreciated!

Update:

Sorry if I wasn't clear enough: the effect I'm looking for is basically this bit without using absolute values.

From the waypoint documentation at http://imakewebthings.com/jquery-waypoints/#docs :

Vertical waypoints may also use the value 'bottom-in-view'. This is a shortcut for a common function that sets the waypoint to trigger when the bottom of the element hits the bottom of the viewport.

$('.thing').waypoint({ offset: 'bottom-in-view' });

This might help.

I solved it the following way, not using jQuery waypoint at all in the end:

$('.post-sharing-side').hide();

var entryheight = $('.entry-content').height();

$(document).scroll(function () {
    var y = $(this).scrollTop();
    if (y > 350 && y < entryheight) {
         $('.post-sharing-side').fadeIn();
    } else {
        $('.post-sharing-side').fadeOut();
    }
});

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