I Like
I Like

Reputation: 1847

how to add a div to an array using jQuery, then use loop and fadeOut method

I am trying to create something similar to a slideshow for a bio page. I wanted to store divs with the ids ('hobbies', 'homeplace', and 'welcome') in an array so I could click on them, and make them disappear one by one, not all at once. As the code shows below, I created an array called arr, and then used a loop in a separate function to make the div elements fade out. Any help would be much appreciated for this beginner coder.

    <body>
    <div class="aboutpage">
    <img src="http://www.2020site.org/trees/images/MatureWalnut.jpg">
    <div id="slideshow">

        <div id="homeplace">
        <img src="http://www.2020site.org/trees/images/MatureWalnut.jpg">
        </div>

        <div id="hobbies" >
        <img src="http://www.allaboutbirds.org/guide/PHOTO/LARGE/red_winged_blackbird_glamour.jpg">
        </div>

        <div id="welcome">
        <h1>What's up!</h1>
        </div>

    </div>
    </div>
    </body>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
    </script>
  <script>

    $(document).ready(function(){
    $var arr=[];
      $("#slideshow div").each(function(){ arr.push($(this));});
    }
    )

    $("#slideshow").click(function(){  
        for (i=0; i<arr.length; i++){  
            $arr[i].fadeOut();
    }
   });
 </script>

Upvotes: 1

Views: 59

Answers (4)

Vikk
Vikk

Reputation: 647

JavaScript is non-blocking by default. So even if you write a loop, all of the animations will fire at once. This is because JavaScript runs asynchronously. In order to get around this, you have to use a little recursion check out this jsfiddle

var divArray = [$('#homeplace'), $('#hobbies')];



function recurse(i) {

if(i <= divArray.length) {

    setTimeout(function() {

        divArray[i].animate({
          opacity: 0
        }, 2000);
        i++;
        recurse(i);

    }, 2000);
}

}

recurse(0);

Upvotes: 1

Ahs N
Ahs N

Reputation: 8366

This with a opacity and slide effect:

$("#slideshow div").click(function() {
  $(this).animate({"opacity": "0"}, 400, function() {
    $(this).animate({"height": "toggle"}, 400);
  });
})

Here is the JSFiddle demo

Upvotes: 1

Chintan Mirani
Chintan Mirani

Reputation: 1465

You want somthing like this?

$(document).ready(function(){
    $("#slideshow").click(function(){
        $("#slideshow div:visible").first().fadeOut();
    });    
});

here is jsfiddle

Upvotes: 1

brk
brk

Reputation: 50291

Do you want to fadeOut all images on a single click or want to fadeOut the image which is clicked. If your requirement is the second one you can use this snippet

$("#slideshow div").click(function(){
   $(this).fadeOut();  //$(this) refers to div which is in current context
})

NOTE: Not sure what exactly $var mean which you have used in your js

DEMO

Upvotes: 0

Related Questions