Devilix
Devilix

Reputation: 323

How to merge Resize and Scroll function - Jquery

Need to change the value of pixels variable for Scrolltop OR make working two functions together.

A fixed bar must appear and disappear after tot pixel scrolled, but if window width change, even the height change, so need to do a little adjustment...

I use this code:

$(document).ready(function() {
    if ($(window).innerWidth() < 501) {
        $('#fixed_bar').css({"top":"50px"});
        var pixels = "270";
    } else {
        $('#fixed_bar').css({"top":"0"});
        var pixels = "500";
    }

    $(window).resize(function(){
        if ($(window).innerWidth() < 501) {
            $('#fixed_bar').css({"top":"50px"});
            var pixels = "270";
        } else {
            $('#fixed_bar').css({"top":"0"});
            var pixels = "500";
        }
    });
    $(window).on("scroll load", function(){
        if ($(this).scrollTop() >= pixels ) { //<-- this var not change when window resize
            $("#fixed_bar").fadeIn(200);
        } else {
            $("#fixed_bar").fadeOut(200);
        }
    });
});

I'm newbie on jquery, but i'm not able to understand why this code is not work.

Hope in your help. Thanks.

Upvotes: 0

Views: 114

Answers (1)

ikiK
ikiK

Reputation: 6532

Move your declaration of variable outside of all events and set the value inside, and not re - declaring it all the time inside.

Now your resize event will update the value and on scroll will use it.

Example: https://jsfiddle.net/u1962kdL/

$(document).ready(function() {
var pixels = ""

    if ($(window).innerWidth() < 501) {
        $('#fixed_bar').css({"top":"50px"});
        pixels = "270";
    } else {
        $('#fixed_bar').css({"top":"0"});
        pixels = "500";
    }

    $(window).resize(function(){
        if ($(window).innerWidth() < 501) {
            $('#fixed_bar').css({"top":"50px"});
            pixels = "270";
        } else {
            $('#fixed_bar').css({"top":"0"});
            pixels = "500";
        }
        //console.log(pixels) 

    });
    
    $(window).on("scroll", function(){
        console.log(pixels) 
        if ($(this).scrollTop() >= pixels ) { //<-- this var not change when window resize
            $("#fixed_bar").fadeIn(200);
        } else {
            $("#fixed_bar").fadeOut(200);
        }
    });
});

Upvotes: 1

Related Questions