2

I have some code which adds a class at a certain page scroll point, which I need for a particular scenario however I do not need this on mobile.

$(window).scroll(function() {
    if ($(".navbar").offset().top > 500) {
        $(".navbar-fixed-top").addClass("top-nav-collapse");
    } else {
        $(".navbar-fixed-top").removeClass("top-nav-collapse");
    }
});

Could I combine this with something like...

function checkWidth() {
    if ($(window).width() < 514) {
        $('#menu2').addClass('f-nav');
    } else {
        $('#menu2').removeClass('f-nav');
    }
}

$(window).resize(checkWidth);

To say switch the classes but only if the width is above say 480px?

I appreciate this is probably newbie but I wondered if the window scroll function could just be part of the if condition?

Jesse Orange
  • 1,527
  • 1
  • 13
  • 43
  • 1
    you could use width but why those values, Id suggest trying device detection such as http://stackoverflow.com/questions/3514784/what-is-the-best-way-to-detect-a-mobile-device-in-jquery – ShufflerShark Oct 20 '16 at 13:36

2 Answers2

0

If you place the conditional check on the event listener as opposed to the action of the event listener, you can save yourself some resources on mobile while also accomplishing your task.

Try:

if ($(window).width() > 514) {
    $(window).scroll(function() {
        if ($(".navbar").offset().top > 500) {
            $(".navbar-fixed-top").addClass("top-nav-collapse");
        } else {
            $(".navbar-fixed-top").removeClass("top-nav-collapse");
        }
    });
}

By doing the conditional check before applying the event listener, you're not adding an event listener on mobile devices and saving the resources it would be using. This also keeps you from having to add any conditional logic to your functionality since it won't be getting called without the scroll listener being applied on devices smaller than 514px.

0

Try out this fiddle:https://jsfiddle.net/cxn6t946/

You need to put if ($(window).width() > 514) inside the scroll function and it will work.

Edited my answer as the previous fiddle had a problem. It worked fine on sceen size >514 and added top-nav-collapse on an offset>500. However on returning to screen size <514 the top-nav-collaspe class remained there. So had to rewrite the fiddle by incorporating resize.

Check out the updated fiddle:https://jsfiddle.net/cxn6t946/1/

Hope this helps.

Aakash Thakur
  • 3,412
  • 8
  • 27
  • 56