Drake Drake - 3 months ago 11
jQuery Question

Make jQuery act dynamically depending on the width of the window

Hello! I've been learning jQuery for a little while now and am trying to sharpen my skills by creating a responsive website. I added a navigation bar, then a big slider, and below it is the main content of the website. Right now, jQuery (as both the menu background and the main background are black) adds a class to the navigation bar in order to turn it white as soon as you scroll past the slider (which has a height of 550px), so it will be easier to read.

Here's the thing: I want jQuery to add that class depending on the width of the window. If it's less than 600px wide, I want the class to be added automatically. Otherwise, I want jQuery to add it as soon as you scroll past the slider (since I hide it when the window is less than 600px wide). My code is below, and it works just fine if I resize the window and then refresh the page, but I want it to add the class dynamically. Do you think it is possible?

I hope I made myself clear (English is not my first language). Let me know if you need me to explain things better! Thank you in advance. :)

if ($(window).width() > 599 ) {
$(window).scroll(function() {
if ($(window).scrollTop() >= 550) { //if you scroll past the slider
$("#main nav").addClass("white-menu");
} else {
$("#main nav").removeClass("white-menu"); //so it turns black again
}
});
} else {
// add it automatically (the slider is hidden):
$("#main nav").addClass("white-menu");
};

Answer

you can use all the code inside scroll event

$(window).scroll(function() {
        if ($(this).scrollTop() >= 550 && $(this).width() <= 599) { //if you scroll past the slider
            $("#main nav").addClass("white-menu");
        } else {
            $("#main nav").removeClass("white-menu"); //so it turns black again
        }
    });

a similar DEMO

about resize you can use

$(window).on('resize',function() {
    $("#main nav").removeClass("white-menu");
});

on window resize the code will remove the class till user scroll then the scroll event will fire after user scrolling

or instead of all of that you can just use

$(window).on('scroll resize',function() {
        if ($(this).scrollTop() >= 550 && $(this).width() <= 599) { //if you scroll past the slider
            $("#main nav").addClass("white-menu");
        } else {
            $("#main nav").removeClass("white-menu"); //so it turns black again
        }
});

DEMO