I'm working on my first more "complex" jQuery code. As a mutation observer only looks for changes I need to to something on the element with a specified class ("active") on page load and then the same thing again on every other element that get's the class ("active"). Currently I'm writing duplicate code ("Do something x") which surely is not a good practice. That's what I currently have so far.
jQuery(document).ready(function($) {
var tabs = document.querySelectorAll(".tab-content");
var active = 'active';
$(tabs).each(function(index){
//Check for the active tab on page load
if($this).hasClass(classtowatch)) { //Do something x }
//Mutation Observer for getting the active tab if tab changes
var target = this;
var config = {attributes: true};
var prevClassState = target.classList.contains(active);
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if(mutation.attributeName == "class"){
var currentClassState = mutation.target.classList.contains(active);
if(prevClassState !== currentClassState){
prevClassState = currentClassState;
// Active Tab
if(currentClassState) {
// Do Something x
}
//Every other tab
else {}
}
}
});
});
});
});
So my question is is there any way to either run the observation on page load or do my "things" for the active element without duplicating the code for it.
To not write duplicate code you can just define a function.
like:
and then you call it whenever needed:
But probably the best solution would not be to use mutationObserver at all but to "hook into" or "adapt to" whatever does the tabbing functionality. By the classname i can imagine its bootstrap? you can checkout the docs for the api https://getbootstrap.com/docs/5.0/components/navs-tabs/#methods