patternjavascriptMinor
Gallery of employees with dynamic filtering
Viewed 0 times
galleryemployeeswithdynamicfiltering
Problem
I'm trying to learn how to write better, more efficient JavaScript code and wanted to run this function I'd written by you and see if people can suggest an improved method.
It's basically a people filter based upon two variables.
Demo.
It works fine, but if additional categories come in (so far there are three) then the code would become redundant.
It's basically a people filter based upon two variables.
Demo.
It works fine, but if additional categories come in (so far there are three) then the code would become redundant.
var family = 'director';
var expertise = 'asset';
function showConsultant(){
$('.profile').stop(true,true).fadeOut(100);
$('.profile[data-family="'+family+'"][data-expertise="'+expertise+'"]').delay(101).fadeIn();
}
showConsultant();
$('.top-level li').on('click', function() {
$('.top-level li').removeClass('selected');
$(this).addClass('selected');
if( $(this).index() === 0 ){
family = 'director';
showConsultant();
} else if( $(this).index() === 1 ){
family = 'consultant';
showConsultant();
} else if( $(this).index() === 2 ){
family = 'support';
showConsultant();
}
});
$('.second-level li').on('click', function() {
$('.second-level li').removeClass('selected');
$(this).addClass('selected');
if( $(this).index() === 0 ){
expertise = 'asset';
showConsultant();
} else if( $(this).index() === 1 ){
expertise = 'insurance';
showConsultant();
} else if( $(this).index() === 2 ){
expertise = 'wealth';
showConsultant();
}
});Solution
Make a lookup table. Then access by index:
If you're worried about going out of bounds, add a range check:
You could even globally define these lists somewhere, so you could write
var expertises = ["asset", "insurance", "wealth"];
expertise = expertises[$(this).index()];
showConsultant();If you're worried about going out of bounds, add a range check:
var expertises = ["asset", "insurance", "wealth"];
var index = $(this).index();
if (0 <= index && index < expertises.length) {
expertise = expertises[index];
showConsultant();
}You could even globally define these lists somewhere, so you could write
enums.getExpertise(index).Code Snippets
var expertises = ["asset", "insurance", "wealth"];
expertise = expertises[$(this).index()];
showConsultant();var expertises = ["asset", "insurance", "wealth"];
var index = $(this).index();
if (0 <= index && index < expertises.length) {
expertise = expertises[index];
showConsultant();
}Context
StackExchange Code Review Q#135274, answer score: 8
Revisions (0)
No revisions yet.