I am building a website template and I wrote this code to pass a variable from a class list. So, in this example, if you have div with a class of modal as well as a class with a prefix of delay- that will be able to set the delay of the modal, directly from the class.
Example:
<div class="modal delay-10 hidden">
Will have a delay of 10 seconds
Here is the code:
const delayselect = document.querySelector(`.${classname}[class*='delay-']`);
const elements = Array.from(delayselect.classList);
const prefix = "delay-";
const matches = elements.filter(function(value){
//get rid of all falsely objects
if(value) {
return (value.substring(0, prefix.length) === prefix);
}
});
const match = matches.toString();
const time = match.split('-').pop();
const delay = time * 1000;
And the way it would be applied would be like this:
setTimeout(function(){
modal.classList.remove('hidden');
}, delay);
This is all just for convenience for the user modifying the template. So they only have to edit the HTML file instead of messing around with the scripts.js file.
I feel like this is a bit clunky though, is there cleaner or simpler way to do this?
hidden? If you're not writing a library that adds JS behavior into CSS, I'm not sure baking variables into CSS class names is the best approach, so a bit more context about what you're building here might be useful so it's easier to evaluate its appropriateness for your goals. \$\endgroup\$