2

I am trying to loop through multiple p elements using JQuery to show and hide them but I just can't get it to work. I've also tried a for loop. The current shows and hides all the p elements and I would like to show and hide them one after the other. Here's my code:

HTML

<p hidden="" class="tweet-1">"Lorem Ipsum"</p>
<p hidden="" class="tweet-2">"Lorem Ipsum"</p>
<p hidden="" class="tweet-3">"Lorem Ipsum"</p>

etc

JQuery

var i=0
    $("p").each(function() {

    $(".tweet-" + i).show().hide();
    i+=1

    });
Ami Ya
  • 33
  • 4

3 Answers3

1

This works for me:

$("[class^=tweet-]").each(function(index){   
  $(this).delay(500*index).fadeIn();  
});

but i need to change the "hidden" attribute in paragraph with css display none.

<p class="tweet-1" style="display:none">"Lorem Ipsum 1"</p>
<p class="tweet-2" style="display:none">"Lorem Ipsum 2"</p>
<p class="tweet-3" style="display:none">"Lorem Ipsum 3"</p>
dantella
  • 66
  • 4
  • Thanks for your response. I might not have been clear enough: I want to fade in tweet-1, fadeout tweet-1 and then fade-in tweet-2, fadeout tweet 2 etc. This method is an improvement to my attempt but it still shows all the p elements simultaneously. – Ami Ya Feb 08 '16 at 19:43
  • Figured it out: if you want the specific effect that I was looking for (fading in/out elements one by one) you need to set index equal to the sum of your fadeIn().fadeOut(). For example (1000*index).fadeIn(500).fadeOut(500); – Ami Ya Feb 08 '16 at 20:19
1

if you want the p elements to show only one at a time then the best way to achieve this functionality is to use jQuery promises. Also, you might consider using i = 1 instead of i = 0 since you do not have a class "tweet-0".

var i=1;
var arrayOfPromises = [];

$("p").each(function() {

    if (i == 1)
    {
        $(".tweet-" + i).show();
    }
    else
    {
        $.when(arrayOfPromises[i-1]).done(function() {
            $(".tweet-" + i).show();
        });
    }

    arrayOfPromises.push($(".tweet-" + i).hide());
    i+=1;
});
Russell Jonakin
  • 1,716
  • 17
  • 18
0

I m not sure to understand.

But fix your js :

var i=0;
$("p").each(function() {
$(".tweet-" + i).show(1000).hide(2000);
i+=1;
});

And I think it will be good that you add a delay(), like : How can I use delay() with show() and hide() in Jquery

Community
  • 1
  • 1
pablofr
  • 134
  • 1
  • 14