Why is my setTimeout function to fadeOut, replace and fadeIn text on delay with jquery's replaceWith() not working?

The replacing happens, the fading doesn't... This is my code:

$(document).ready(function() {
var delay = 3000; //3 seconds

setTimeout(function(){
  $('.header p').fadeOut(300, function(){
    $('.header p').replaceWith("<p>A LIFESTYLE FOR EVERYONE</p>");
  });
  $('.header p').fadeIn(300);
}, delay);
console.log("replaced");
});

Upvotes: 0

Views: 445

Answers (2)

Jan Sch&#228;r
Jan Sch&#228;r

Reputation: 828

Try using text instead of replaceWith, and put fadeIn inside your callback:

$(document).ready(function() {
var delay = 3000; //3 seconds

setTimeout(function(){
  $('.header p').fadeOut(300, function(){
    $('.header p').text("A LIFESTYLE FOR EVERYONE").fadeIn(300);
  });

}, delay);
console.log("replaced");
});

If you do replaceWith, you are creating a new p which isn't faded out. Also, you want to fade it in after it's faded out (not at the same time).

Upvotes: 1

charlietfl
charlietfl

Reputation: 171669

Replacing the element is problematic when you don't hide new one, change it's content instead

You can avoid multiple dom searches for the same element by chaining things inside the callback of first animation

setTimeout(function(){
     $('.header p').fadeOut(300, function(){
            $(this).text("A LIFESTYLE FOR EVERYONE").fadeIn(300);        
     });
}, delay);

By only replacing the content it keeps the reference to element and allows chaining

Upvotes: 2

Related Questions