javascriptjqueryhtmlcss

Jquery, how to: firstly fadeout clicked div, later the others


HTML

<div id="wrapper">
<div class="test1">
    <img src="x-led.png">
</div>
<div class="test2">
    <img src="x-led.png">
</div>
<div class="test3">
    <img src="x-led.png">
</div>
</div>

JQUERY

<script>
$('#wrapper img').click(function() {
var to = 10000;
var from = 1000;
var number1 = Math.floor(Math.random()*(to-from+1)+from);
var number2 = Math.floor(Math.random()*(to-from+1)+from);
var number3 = Math.floor(Math.random()*(to-from+1)+from);

$('.test1').fadeOut(1000, function() {
    $('.test1').html('You Won: ' + number1).fadeIn(3000);
});
$('.test2').fadeOut(1000, function() {
    $('.test2').html('You Won: ' + number2).fadeIn(3000);
});
$('.test3').fadeOut(1000, function() {
    $('.test3').html('You Won: ' + number3).fadeIn(3000);
});
 });
 </script>

Hello. I want to ask how to make, to firstly fadeout and fadein clicked DIV, and after the others div ?

And maybe it could be done more compact with cycles (for, while) or something, because i dont think its normal to do like this.

Sorry, i'm new to javascript, but i'm php programmer.


Solution

  • Well, @Dryden Long's answer is workable for the problem as presented, but it nests pretty deeply as soon as we start adding more divs. Another solution (assume each div has a data attribute containing the appropriate number. Even more appropriately, store the number in a memory object rather than attaching it to the DOM) relies on iterating over the element's siblings():

    var $clickedImg = $(e.target);
    var $clickedDiv = $clickedImg.parent();
    var $siblings = $clickedDiv.siblings();
    
    $clickedDiv.fadeOut(1000, function () {
        $clickedDiv.html('You Won: ' + $clickedDiv.data('num')).fadeIn(3000, function () {
            $siblings.each(function (i, e) {
                var $sib = $(e);
                $sib.fadeOut(1000, function () {
                    $sib.html('You Won: ' + $sib.data('num')).fadeIn(3000);
                });
            });
        });
    });
    

    See http://jsfiddle.net/Palpatim/qk4Ba/ for a demo.