Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fading a paragraph in word by word using jquery?

    <p class="example">i want to split this paragraph into 
words and fade them in one by one</p>

the jquery/js:

$(document).ready(function() {

    var $txt = $(".example")
       ,$words = $txt.text()
       ,$splitWords = $words.split(" ");

    $txt.hide();

    for(i = 0; i < $splitWords.length; i++){
     // i want fade in each $splitWords[i]
     //$splitWords[i].fadeIn(....  - i tried this doesnt work

   }
  });

im trying to split the paragraph into words, and fade them in one by one, thier might be an easier way to do this without splitting the words, please shed some light on this. thanks

like image 491
unknown Avatar asked Jul 24 '12 19:07

unknown


People also ask

How do I fadeOut text in JQuery?

The jQuery fadeOut() method is used to fade out a visible element. Syntax: $(selector).fadeOut(speed,callback); The optional speed parameter specifies the duration of the effect.

How does JQuery fadeOut work?

fadeOut() method animates the opacity of the matched elements. Once the opacity reaches 0, the display style property is set to none , so the element no longer affects the layout of the page. Durations are given in milliseconds; higher values indicate slower animations, not faster ones.

What is the use of fadeOut?

Definition and Usage The fadeOut() method gradually changes the opacity, for selected elements, from visible to hidden (fading effect). Note: Hidden elements will not be displayed at all (no longer affects the layout of the page). Tip: This method is often used together with the fadeIn() method.


1 Answers

Text by itself can't have an opacity, therefore you must wrap the text with an element that can have opacity (such as a span). You can then fade in those spans.

Try this:

http://jsfiddle.net/6czap/

var $el = $(".example:first"), text = $el.text(),
    words = text.split(" "), html = "";

for (var i = 0; i < words.length; i++) {
    html += "<span>" + words[i] + " </span>";
}

$el.html(html).children().hide().each(function(i){
  $(this).delay(i*500).fadeIn(700);
});

Update for benekastah: http://jsfiddle.net/6czap/3/

var $el = $(".example:first"), text = $.trim($el.text()),
    words = text.split(" "), html = "";

for (var i = 0; i < words.length; i++) {
    html += "<span>" + words[i] + ((i+1) === words.length ? "" : " ") + "</span>";
};
$el.html(html).children().hide().each(function(i){
  $(this).delay(i*200).fadeIn(700);
});
$el.find("span").promise().done(function(){
    $el.text(function(i, text){
       return $.trim(text);
    });            
});
like image 143
Kevin B Avatar answered Oct 12 '22 01:10

Kevin B