I am writing a (multi)filter that is created when the user enters in the data through wordpress. There can be anywhere between 2 – 10 filters so I need this to be as dynamic as possible. My first approach was to write out a boolean for each possible filter being created and check if it is there or not. Inside the boolean is a click function that checks if the data===”yes” and then add a active class to the item. I rewrote it in a do while, but am not sure if this is the best approach or if they are both bad.
I am not looking for a complete answer or working example, but rather if my way makes sense? If so why? if not, why not? And an explanation of how I could possible improve it or think of it in a different way.
manually Check
var mem = $(".member");
var filter1 = $(".filter-1");
var filter2 = $(".filter-2");
var filter3 = $(".filter-3");
var memCom1 = $(".member").data("com-1");
var memCom2 = $(".member").data("com-2");
var memCom3 = $(".member").data("com-3");
// DO THIS FOR ALL POSSIBLE
if (memCom1.length > 0 || filter1.length > 0) {
filter1.click(function() {
var com1 = $(this).data("com-1");
if(com1 === "yes") {
$(this).addClass(active);
}
});
}
if (memCom2.length > 0 || filter2.length > 0) {
filter2.click(function() {
var com2 = $(this).data("com-2");
if(com2 === "yes") {
$(this).addClass(active);
}
});
}
if (memCom3.length > 0 || filter3.length > 0) {
filter3.click(function() {
var com3 = $(this).data("com-3");
if(com3 === "yes") {
$(this).addClass(active);
}
});
}
// would go up to 10
DO WHILE
var mem = $(".member");
var active = "is-active"
do {
var i = 1;
if ( $(".member").data("com-"+i).length > 0 || $(".filter"+i).length > 0 ) {
$(".filter-"+i).click(function() {
if( $(this).data("com-"+i) === "yes" ) {
$(this).addClass(active);
}
});
}
i++;
}
while (i <= mem.length);
In your case, using $.each() instead of do-while will have cleaner code. Also, I think having the same attribute “com” would simplify than “com-#”. For problem like these, its helpful to post a jsfiddle.
without knowing more details about you app, your second approach using do-while looks preferable because it uses less code and is easier to maintain/extend. However, it looks like you can reuse ‘mem’ variable in your if condition.