ModController.js
About
This tool helps to control BEM classes.
Guide
Initialization
After initialisation block classname is added to element.
// new ModController(htmlElement, bemBlockOrElementName)
// HTML:
// <div id="block"></div>
const block = document.getElementById('block');
const blockModController = new ModController(block, 'Block');
// HTML:
// <div id="block" class="Block"></div>
"setMod" method
setMod method adds modificator classname to element. Default value is true
// setMod(name, value, redraw)
// HTML:
// <div id="block" class="Block"></div>
blockModController.setMod('big');
blockModController.setMod('color', 'red');
// HTML:
// <div id="block" class="Block Block_big Block_color_red"></div>
blockModController.setMod('small'); // will not rewrite Block_big classname
blockModController.setMod('color', 'green'); // will rewrite Block_color_red classname
// HTML:
// <div id="block" class="Block Block_big Block_small Block_color_green"></div>
Remove modificator
Set value to false or null to remove the modificator. "0" number or undefined will not remove the modificator.
// HTML:
// <div id="block" class="Block"></div>
blockModController.setMod('count', 0);
// HTML:
// <div id="block" class="Block Block_count_0"></div>
blockModController.setMod('count', null);
// HTML:
// <div id="block" class="Block"></div>
Remove modificator and set it back again
Sometimes you need to keep the same classname, but trigger its creation. For example play animation that related to it. For that purpose you can set redraw argument in setMod function to true.
// CSS:
// @keyframes jump { 50% { bottom: 0.5rem; } }
// .Block_jumping {
// position: relative;
// bottom: 0;
// animation: jump 0.5s;
// }
blockModController.setMod('jumping');
setInterval(() => {
blockModController.setMod('jumping', true, true); // jump animation will be triggered again
}, 1000);
Remove all modificators
To remove all modificators, use removeAllMods method
// removeAllMods()
// HTML:
// <div id="block" class="Block"></div>
blockModController.setMod('big');
blockModController.setMod('color', 'red');
// HTML:
// <div id="block" class="Block Block_big Block_color_red"></div>
blockModController.removeAllMods();
// HTML:
// <div id="block" class="Block"></div>
Sources
The sources can be found on Github:
And if you love TypeScript as I am, here is the link for you: