Simpliflying jQuery calls that use redundant data
-
05-07-2021 - |
Question
I have a bit of code that controls some div
s but its repeats a lot just for one little change on a different link
If I click #Option1
then 2-5 shrink to 0 (if any of them are open) and go to 0 opacity
and vice versa if you click 2 (collapsing 1 and the rest) but i cant think of a good way to make it more generic but there has to be a way
$('#Option1').click(function() {
var ele = $('#Option1Div');
ele.animate({
opacity : .75,
width : '602px'
}, 5000, function() {
// Animation complete.
});
var ele = $('#Option2Div');
ele.animate({
opacity : 0.1,
width : '0px'
}, 5000, function() {
// Animation complete.
});
var ele = $('#Option3Div');
ele.animate({
opacity : 0.1,
width : '0px'
}, 5000, function() {
// Animation complete.
});
var ele = $('#Option4Div');
ele.animate({
opacity : 0.1,
width : '0px'
}, 5000, function() {
// Animation complete.
});
var ele = $('#Option5Div');
ele.animate({
opacity : 0.1,
width : '0px'
}, 5000, function() {
// Animation complete.
});
});
Solution
You can try this
$('#Option1 , #Option2 ,#Option3 , #Option4 , #Option5').click(function() {
var ele = $('#' + this.id + 'Div');
ele.animate({
opacity: .75,
width: '602px'
}, 5000, function() {
// Animation complete.
});
$('[id^="Option"][id$="Div"]').not(ele).animate({
opacity: 0.1,
width: '0px'
}, 5000, function() {
// Animation complete.
});
});
OTHER TIPS
If you give your options a class of options
and your divs a class of option-divs
, you can use something like this:
$('.options').click(function() {
var element = $('.option-divs').eq($(this).index());
element.stop().animate({
opacity: .75,
width: '602px'
}, 5000).siblings().stop().animate({
opacity: 0.1,
width: '0px'
}, 5000);
});
Technically, as you have different values for opacity, width, and eventually duration of animation, you cannot do a job purely generic.
But you could isolate all changing data in array and apply a generic code like:
var opacities = [0.75, 0.1, 0.1, 0.1, 0.1];
var widths = [602, 0, 0, 0, 0];
var durations = [500, 500, 500, 500, 500];
var callbacksComplete = [cb1, cb2, cb3, cb4, cb5];
$('#Option1').click(function() {
// Assume that 3 arrays have the same size !
for(var i = 0 ; i < opacities.length ; i++)
{
$('#Option' + i + 'Div').animate({
'opacity' : opacities[i],
'width' : widths[i]
}, durations[i], callbacksComplete[i]);
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow