Blueone Blueone - 1 month ago 15
Javascript Question

Div follow as you scroll on desktops screen and is fixe on mobile screen

I want a div follow as you scroll when you are on a screen wider than 991. On a screen size smaller i want the div fixe. And i want the javascript code refresh every time someone load or resize the page.

Here my code (it's not dry...).

My problem is when i resize the window (desktop screen -> mobile screen -> desktop screen...):
1 - on mobile screen i can't go at the bottom of the page
2 - on desktop screen i have a problem when i scroll the page

//when the page is load and the window resize detect if it's a smallscreen
var smallscreen = true;
$(window).on("resize load", function() {
if ($(window).width() > 991) {
smallscreen = false;
}
else {
smallscreen = true;
};

//if it's not a small screen activate the scrolling
if (smallscreen == false) {
$.fn.followTo = function ( pos ) {
var $this = this,
$window = $(window);

$window.scroll(function(e){
if ($window.scrollTop() > pos) {
$this.css({
position: 'absolute',
top: pos
});
}
else {
$this.css({
position: 'fixed',
top: 180
});
};
});
};
$('#checkout_validation').followTo(400);
}
else {
$.fn.followTo = function ( pos ) {
var $this = this,
$window = $(window);

$window.on("resize scroll load", function(e){
if ($window.scrollTop() > pos) {
$this.css({
position: 'initial',
width: '100%',
top: 0
});
}
else {
$this.css({
position: 'initial',
width: '100%',
top: 0
});
};
});
};
$('#checkout_validation').followTo(0);
};
});

Answer Source

Here's my working code. Thanks you @iMatoria for having dried it.

//when the page is load and the window resize detect if it's a smallscreen
var smallscreen = true;

$.fn.followTo = function(pos) {
    var $this = this,
        $window = $(window);

    $window.on("resize scroll", function(e) {
        function positionByScreen(positionForBiggerScreen, topOffsetForBiggerScreen) {
            if (smallscreen == false) {
                //alert('bigcreen scroll end');
                $this.css({
                    position: positionForBiggerScreen,
                    top: topOffsetForBiggerScreen
                });
            } else {
                //alert('smallscreen no scroll end ');
                $this.css({
                    position: 'inherit',
                    top: 0
                });
            }
        }

        if ($window.scrollTop() > pos) {
            positionByScreen("absolute", pos);
        } else {
            positionByScreen("fixed", 180);
        };
    });
};

$(window).on("resize load", function() {
    smallscreen = !($(window).width() > 991);

    //if it's not a small screen activate the scrolling
    $('#checkout_validation').followTo(smallscreen ? 0 : 400);

    //var d = document.getElementById("checkout_validation");
    //d.className += " otherclass";
});