I have a div with several paragraphs inside of it. I want each of these paragraphs to fade in one after the other. I can do that with the following code. However, since I will have many more divs with many other paragraphs, each with their unique class names, I wonder if there is an easier way to achieve this, without keep copy-pasting the code, changing the class names each time.
$('.line1').css('visibility','visible').hide().fadeIn(1000, function(){
$('.line2').css('visibility','visible').hide().fadeIn(1000, function(){
$('.line3').css('visibility','visible').hide().fadeIn(1000, function(){
$('.line4').css('visibility','visible').hide().fadeIn(1000);
});
});
});
.line1, .line2, .line3, .line4 {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="div1">
<p class="line1">Text 01</p>
<p class="line2">Text 02</p>
<p class="line3">Text 03</p>
<p class="line4">Text 04</p>
</div>
Class names don't matter here, you can use .line
or .line{i}
or anything else, as long as there is an easy way to select all of them.
If you want different class names you could use .div1 > p
in place of .line
in the code.
If slight (+/- few milliseconds) innaccuracies aren't an issue, you could use setTimeout for this.
$(".line").each(function (i) {
$(this).css("opacity", 0);
setTimeout(() => {
$(this).animate({ opacity: 1 }, 1000);
}, 1000 * i);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="div1">
<p class="line">Text 01</p>
<p class="line">Text 02</p>
<p class="line">Text 03</p>
<p class="line">Text 04</p>
</div>
You can also use .delay
instead of setTimeout.
$(".line").each(function (i) {
$(this).css("opacity", 0).delay(1000 * i).animate({ opacity: 1 }, 1000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="div1">
<p class="line">Text 01</p>
<p class="line">Text 02</p>
<p class="line">Text 03</p>
<p class="line">Text 04</p>
</div>