I would like to know how to iterate over the h1 element, and get each word to fade in one after the other.
I got it done, but the code is not dry. Can someone please show and explain how to do this with a loop?
$('document').ready(function() {
$('#H').fadeIn(3000).removeClass("hidden").addClass("hColor1");
$('#e').fadeIn(5000).removeClass("hidden").addClass("hColor2");
$('#l').fadeIn(6000).removeClass("hidden").addClass("hColor3");
$('#secondL').fadeIn(7000).removeClass("hidden").addClass("hColor4");
$('#o').fadeIn(7300).removeClass("hidden").addClass("hColor5");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="container">
<h1 class="hidden"><span id="H">Hello</span> <span id="e">everyone</span> <span id="l">lets</span> <span id="secondL">learn</span> <span id="o">javascript</span></h1>
</div>
I wouldn't hide the < h1 > but the spans inside, then use setTimeout() to delay each fadeIn()
$('document').ready(function(){
var spans = $("h1").find("span"); // Get all spans inside <h1>
spans.hide(); // hide spans
var show_time = 1000; // set time for first span
$.each(spans, function(i, item){ // item = every span
setTimeout(function(){ // setTimeout delays events
$(item).fadeIn('slow') // fadeIn to show each item (span)
}, show_time); // showtime after function inside setTimeout
show_time = show_time + 1000; // increase 1 sec for every span
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h1 class="">
<span id="H">Hello</span>
<span id="e">everyone</span>
<span id="l">lets</span>
<span id="secondL">learn</span>
<span id="o">javascript</span>
</h1>
</div>
The code below does the following:
The last step is accomplished by passing a function as the second parameter to the .fadeIn() function. That function is called after the element is finished fading in.
The fading is done in a function named fadeInNext(). That function is called initially for the first child element, but it calls itself for the next element when the fading is finished. That will continue until all child elements have been faded in.
$(function() {
var $header = $('#hdr');
$header.html($.map($header.text().split(/\s+/), function(word) {
return '<span>' + word + '</span>';
}).join(' ')).children().hide().end().show();
(function fadeInNext($element) {
$element.fadeIn('slow', function() {
fadeInNext($element.next());
});
})($header.children(':first'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 id="hdr" style="display: none;">Hello everyone lets learn javascript</h1>
jsfiddle showing the code in re-usable functions.
jsfiddle fading in letters, instead of words.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With