I’m struggling to find a solution that allows me to update the following code to include additional classes. E.g. in addition to .section–bg1, I’d like to include .section–bg2. and .section–bg3.
For further context, here’s a Fiddle:
How can I include the red coloured background section (.section–bg2) in the JavaScript?
I’ve tried "el.classList.contains('section--bg1', 'section--bg2');
" but that is not working. What am I missing?
// active section
if ( (sectionTop <= replaceItemBottom) && (sectionBottom > replaceItemTop)) {
// check if current section has bg
currentSection = el.classList.contains('section--bg1');
// switch class depending on background image
if ( currentSection ) {
replaceContainer[0].classList.remove('js-replace--reverse');
} else {
replaceContainer[0].classList.add('js-replace--reverse')
}
}
4
Answers
To include multiple classes in the el.classList.contains() check, you should use separate classList.contains() calls for each class you want to check. Here’s how you can modify your code to include both .section–bg1 and .section–bg2:
Use
matches()
to check whether an element contains ANY of classes:https://developer.mozilla.org/en-US/docs/Web/API/Element/matches
Applying to your code, use also
classList.toggle()
to make the code shorter:The contains method only accepts a single
token
.You need to call the method twice with each different class and AND the conditions:
If you want to be fancy, you can write a convenience function:
You can’t do that using
classList.contains
, but maybe this alternative works for you: