asanas asanas - 16 days ago 5
Javascript Question

Scroll nested within resize

I have written some jquery and my objective is this:

If screen size is greater than 981, then I want to track the scroll event and do some css changes.

If screen size is less than 981, then I don't want to track the scroll event and instead simply apply some css styles.

And I want to check this condition during resizing also.

My jquery code is below, but the problem is that when I resize the window and while resizing, make it below 981 width, then the scroll event continues to get tracked and things within it get executed.

$(window).on("resize", function () {
var screenwidth = $(window).width();
if ( screenwidth > 981) {
$(window).scroll(function()
{
var wintop = $(window).scrollTop(), docheight = $(document).height(), winheight = $(window).height();

if ( wintop>100)
{
//always in view
console.log('test100');
$('#slider-top-box').css({ "position":"relative","margin-top":"70px" });
$('#news-top-box').css({ "z-index":"1","margin-top":"-70px","background-color":"transparent","padding":"inherit" });
}
else
{
$('#slider-top-box').css({ "position":"fixed","margin-top":"0px" });
$('#news-top-box').css({ "z-index":"1","margin-top":"0px","background-color":"transparent","padding-top":"380px" });
}
});
} else {
$('#slider-top-box').css({ "position":"relative","margin-top":"0px" });
$('#news-top-box').css({ "padding-top":"50px" });
}}).resize();

Answer

Delete the event handler when you don't want it tracked.

Use $(window).off("scroll"); in your else statement:

        $(window).on("resize", function () {
var screenwidth = $(window).width();
if ( screenwidth > 981) {
    $(window).scroll(function()
{   
    var wintop = $(window).scrollTop(), docheight = $(document).height(), winheight = $(window).height();

    if ( wintop>100)
    {
        //always in view
                    console.log('test100');
        $('#slider-top-box').css({ "position":"relative","margin-top":"70px" });
                    $('#news-top-box').css({ "z-index":"1","margin-top":"-70px","background-color":"transparent","padding":"inherit" });
    }
    else
    {
                    $('#slider-top-box').css({ "position":"fixed","margin-top":"0px" });
                    $('#news-top-box').css({ "z-index":"1","margin-top":"0px","background-color":"transparent","padding-top":"380px" });
    }
});
} else {
    $(window).off("scroll");
    $('#slider-top-box').css({ "position":"relative","margin-top":"0px" });
    $('#news-top-box').css({ "padding-top":"50px" });
}}).resize();