2

I'm just wondering if there is a way to condense this script? My JS is pretty rough, but it seems like I should be able to just insert an or operator to add the class of shrink to any class that passes, I can't seem to get the syntax correct though. It just seems like a lot of redundancy.

$(window).scroll(function() {
  if ($(document).scrollTop() > 50) {
    $('nav').addClass('shrink');
  } else {
    $('nav').removeClass('shrink');
  }
    if ($(document).scrollTop() > 50) {
    $('.nav a').addClass('shrink');
  } else {
    $('.nav a').removeClass('shrink');
  }
    if ($(document).scrollTop() > 50) {
    $('.navbar-brand').addClass('shrink');
  } else {
    $('.navbar-brand').removeClass('shrink');
  }
});

Or is there a way to add a class to all children of a given element?

B. Bailey
  • 21
  • 3

3 Answers3

7
$(window).on('scroll', function() {
    $('nav, nav a, .navbar-brand').toggleClass('shrink', $(this).scrollTop() > 50);
});

Using the multiple selector to target all matching elements, and toggleClass to toggle the class based on the second argument, being the "state".
this references the window inside the event handler, and $(window).scrollTop() should be the same as $(document).scrollTop() 99.99% of the time.

Community
  • 1
  • 1
adeneo
  • 312,895
  • 29
  • 395
  • 388
1

Probably something like this?

$(window).scroll(function() {
  if ($(document).scrollTop() > 50) {
       $('nav, .nav a, .navbar-brand').addClass('shrink');
    } 
  else {
       $('nav, .nav a, .navbar-brand').removeClass('shrink');
  }  
});
Dmitry Komin
  • 549
  • 6
  • 7
0

You could try:

$(window).scroll(function() {
    if ($(document).scrollTop() > 50) {
        $('nav, .nav a, .navbar-brand').addClass('shrink');
    } else {
        $('nav, .nav a, .navbar-brand').removeClass('shrink');
    }
});

Have a look at: https://api.jquery.com/multiple-selector/

Roland Krinner
  • 421
  • 2
  • 10