Kenneth Rhodes Kenneth Rhodes - 27 days ago 9
AngularJS Question

if ($(window).width() < 768) {} not working when browser resizes. How do I fix this?

I'm trying to make it so that only when the browser is less than 768px, my navigation bar items will toggle hidden or shown when an element with "navlogo" is clicked. I know I'm not the most descriptive, but here's my code.

if ($(window).width() < 768) {

$(".navlogo").click( function (){
$(".navwrapper").toggle();
});
$(".navitem").click( function (){
$(".navwrapper").hide();
});

}


I know this is actually going to get marked as a duplicate but it's not. The thing is that I want it to be able to even work without refreshing. If it requires Angular.js then it would be helpful to know what code to use for that because I wouldn't mind using it but yeah I just want for the user to not have to refresh every time to get the correct result.

Also, one bug that happens when I don't have the

if ($(window).width() < 768) {}


is that yes it still works properly but even if the website is not in mobile mode, which occurs when the max width is 768px or lower, when the user clicks the element with "navlogo," it still hides the "navwrapper." That's not bad but the thing is that I also want it to hide when a user clicks on an element with "navitem."

Thank you!

Answer

The if statement should be inside the click function:

$(".navlogo").click( function (){
    if ($(window).width() < 768) {
        $(".navwrapper").toggle();
    }
});
$(".navitem").click( function (){
    if ($(window).width() < 768) {
        $(".navwrapper").hide();
    }
});

Edit:

To hide/show the .navwrapper when the window is resized you can listen to the window resize event.

$(window).on('resize', function(e) {

    if ($(window).width() > 767 && $(".navwrapper").is(':hidden')) {
        $(".navwrapper").show();
    }

});

Some considerations:

  • Try to use variables for selectors that will be called several times
  • For efficiency try to enclose what happens in the resize function in a timeout
  • Try to use CSS where possible for responsive instead of JavaScript