I've written some jQuery for my navbar, but it's super sloppy and I'm always trying to write better code.

    var sT = $(this).scrollTop();
    if (sT >= 70) {
        $('.navbar .scroll-link').addClass('navbar-link-switch')
        $('.navbar .logo').addClass('logo-adjust')
        $('.navbar hr').addClass('hide')
        $('.navbar .navbar-collapse').addClass('border')
    } else {            
        $('.navbar .scroll-link').removeClass('navbar-link-switch')
        $('.navbar .logo').removeClass('logo-adjust')
        $('.navbar hr').removeClass('hide')
        $('.navbar .navbar-collapse').removeClass('border')

My goal is that, when the user scrolls pass a certain limit, my navbar removes certain classes and adds certain classes.

  • \$\begingroup\$ What you could do is add only ONE class, say "switch", just to the main navbar. Then act on elements differently, whether they belong to "navbar" or to "navbar.switch". You can, for instance, have navbar button { background : blue } and navbar.switch button { background : green }. The color of the button will change depending on scrollTop value. \$\endgroup\$ – Jeremy Thille Mar 25 '15 at 16:57
  • \$\begingroup\$ Any chance you can share your HTML too? Do you have control over your HTML? Might be easier to use Bootstrap's built-in ability to toggle. \$\endgroup\$ – Blexy Mar 31 '15 at 4:07

Is hard to evaluate without the html but, considere introduce toggleClass.

$element.toggleClass(className, condition);


If your jQuery version doesn´t allow it, you can introduce as a separate function:

function toggleClass($element, class, condition) {
   condition ? $element.addClass(class) : $element.removeClass(class);

and the full solution: http://jsfiddle.net/cbhvteon/1/

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy