Select multiple body classes in DOM-based Routing

Continuing the discussion from JavaScript only on certain pages:

How would you select multiple body classes for a section of javascript?

    home, tax_discipline: {
      init: function() {
        // JavaScript to be fired on the home and taxonomy archive page
      }
    }

This example results in Expected ‘:’ and instead saw ‘,’ jshint errors
Thanks!

I think this is the only solution:

Roots = {
  home: {
    init: function () {
      // do stuff
    }
  }
}

Roots.tax_discipline = {
  init: Roots.home.init
}

You can’t self-reference the top level object in JS, so we just set the other property after it.

1 Like

Thanks, that did the trick!

Let’s say you only want a piece of the home javascript on the taxonomy archive, can you subdivide the home javascript into portions and use only one portion or do they always have to be called init?
Something like this:

Roots = {
  home: {
    init: function () {
      // do stuff
    },
    isotope: function () {
      // initialize isotope
    }
  }
};
Roots.tax_discipline = {
  init: Roots.home.isotope
};

Thanks!

i do it a bit differently. i add a class via body_class filter and add the new class in to _main.js

for instance if i want to initialize isotope on home and a taxonomy “discipline” first i filter the body class and add a class to body

/**
 * Add body class to call JS
 */

function my_body_class($classes) {
  // Isotope
  if (is_home() || is_tax('discipline')) {
    $classes[] = 'isotope';
  }
  return $classes;
}
add_filter('body_class','my_body_class');

than i add the body class in _main.js

  // Isotope
  isotope: {
    init: function() {
        // initialize isotope
    }
  }

i know you are adding another class to the body which maybe does not look nice but it’s easier when you decide that you want to fire the script on another page, tax, archive… than you just add your conditional to the my_body_class() function.

anyway… that’s my 2 cents in…

1 Like

That’s actually a very handy method to control which portions of javascript are fired on multiple pages.
Thanks!

A quick method without needing to extend the Roots object or add any filters is to do a check in the common init function,

var Roots = {
  // All pages
  common: {
    init: function() {
      if($('body').is('.home, .tax-dicipline')){
        // init isotope or call your extended Roots object function
        
      }
    }
  }
}

Kind of goes against the whole principal of dom based routing but will work and with less code