waffl waffl - 6 months ago 11
jQuery Question

fadeIn called in callback of fadeOut blinking or occurring twice on certain items?

I am using a

select
form element to show different days for a schedule. For some reason, the third and fourth days are blinking when chosen and I'm not sure why. And if the third or fourth days are selected, it causes other days to blink when chosen.

Example available here:
http://jsfiddle.net/waffl/WBHQc/1/

HTML:

<select id="date-select" name="date">
<option value="day1" selected="selected">Thursday</option>
<option value="day2">Friday</option>
<option value="day3">Saturday</option>
<option value="day4">Sunday</option>
</select>

<div id="schedule">
<div id="day1"><img src="http://placehold.it/350x150"></div>
<div id="day2"><img src="http://placehold.it/350x150/ff00000"></div>
<div id="day3"><img src="http://placehold.it/350x150/37FDFC"></div>
<div id="day4"><img src="http://placehold.it/350x150/FFC125"></div>
</div>


CSS:

#day2, #day3, #day4 {
display: none;
}


JS:

$('#date-select').change(function() {
var newDay = $(this).val();
$("#schedule > div").fadeOut(200,function() {
$("#schedule #"+newDay).fadeIn();
});
});

Answer

Seems to be a timing related issue. Using #schedule > div as your selector causes all divs to start fading out, and then each triggering the fadeIn of the div. For the most straightforward solution, I'd probably just cache off the currently selected div and then use that to fade out (only fade out one rather than all of them):

var sel = $('#day1');
$('#date-select').change(function() {
    var newDay = $(this).val();
    $(sel).fadeOut(200,function() {
        $("#schedule #"+newDay).fadeIn(function(){
            sel = this;
        });
    });
});

Fiddle here

Comments