Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I float an element on scroll, with delay?

I have the following div floating but I want as the green element inside left panel to have a delay about half second.

Does anyone any idea how can I do this?

https://jsfiddle.net/eoopvgmc/22/

This is the code which is floating the elements on scroll

$(document).ready(function() {
        var offset = $('.ads').offset().top, top;
        $(document).on('scroll', function() {
            top = $(window).scrollTop() < offset ? '0' : $(window).scrollTop() - offset + 'px';
            $('.ads').css({
                'top': top
            });
        })
    }); 
like image 405
Markus Hayner Avatar asked Dec 09 '22 02:12

Markus Hayner


2 Answers

To make the .element independent transition, you need to move it out of the .left-zone element.

$(document).ready(function () {
    var offset = $('.ads').offset().top,
        top;
    $(document).on('scroll', function () {
        top = $(window).scrollTop() < offset ? '0' : $(window).scrollTop() - offset;
        console.log(top);
        $('.ads').css({
            'top': top
        });
        $('.element').css({
            'top': +top + 50
        });
    })
});

Working Fiddle

like image 117
Mr_Green Avatar answered Dec 10 '22 15:12

Mr_Green


I managed to get something like what you describe working by adding some transition effects to the element and using a little delay, you should be able to tweak the timeout, margin-top and transition values to get exactly what you want:

$(document).ready(function() {
    var offset = $('.ads').offset().top, top;
    $(document).on('scroll', function() {
        top = $(window).scrollTop() < offset ? '0' : $(window).scrollTop() - offset + 'px';
        $('.ads .element').css({
            'transition': 'none',
            'margin-top': '-60px'
        });
        $('.ads').css({
            'top': top
        });
        setTimeout(function() {
            $('.ads .element').css({
                'transition': 'margin-top 3s',
                'margin-top': '0'
            });
        });
    })
});

Fiddle: https://jsfiddle.net/yckszc16/

like image 28
Starscream1984 Avatar answered Dec 10 '22 16:12

Starscream1984