John Black
John Black

Reputation: 305

jQuery UI replaceWith() animation?

So I have a div:

<div id="lol">
Some random text!
</div>

And I have other div:

<div id="happy">
lol
</div>

How could a make an animation, in which the first div is smoothly replaced by the second one? If a Do a fadeIn/fadeOut, the second div would only starting to happear after the first div was gone.

Upvotes: 0

Views: 3743

Answers (6)

dc5
dc5

Reputation: 12441

Using fadeOut/fadeIn will work if you use absolute positioning. There are many other options as well.

I'm not at all sure what you would like to see in your final result, but here are a few examples:

Example fiddle

CSS:

div.container {
    position: relative;
    height: 30px;
}
div.container div {
    position: absolute;
    top: 0;
    left: 0;
}

HTML:

<div class="container">
    <div id="lol">Some random text!</div>
    <div id="happy" style="display: none">lol</div>
</div>
<div class="container">
    <div id="lol1">Some random text!</div>
    <div id="happy1" style="display: none">lol</div>
</div>
<div class="container">
    <div id="lol2">Some random text!</div>
    <div id="happy2" style="left: -200px">lol</div>
</div>
<div class="container">
    <div id="lol3">Some random text!</div>
    <div id="happy3" style="left: 200px; opacity: 0;">lol</div>
</div>

Sample code:

$('#lol').fadeOut(1000);
$('#happy').fadeIn(1000);


$('#lol1').slideUp(1000);
$('#happy1').slideDown(1000);

$('#lol2').animate({left: -200});
$('#happy2').animate({left: 0});


$('#lol3').animate({left: -200}, 1000);
$('#happy3').animate({left: 0, opacity: 1}, 1500);

Upvotes: 0

Tricky12
Tricky12

Reputation: 6820

You can add a class to both of these divs, then toggle the class. This will allow both to toggle simultaneously (one fades in at the same time the other is fading out).

HTML

<div id="lol" class="toggle">
Some random text!
</div>
<div id="happy" class="toggle">
lol
</div>
<button id="btn">Replace</button>

JQuery

$("#happy").hide();

$("#btn").click(function() {
    $(".toggle").toggle(2000);
});

JSFiddle

Upvotes: 0

Igor Martins
Igor Martins

Reputation: 2047

I think that is what do you want:

$("button").click(function () {
$(".happy").toggle('slow');
});

JSFIDDLE

Upvotes: 0

Mithun Satheesh
Mithun Satheesh

Reputation: 27855

I think simply this would work.

$("#happy").hide();

$("#smooth").click(function(){

    $("#happy").show();//no transition for this
    $("#lol").slideUp();//with transition


});

here is a demo fiddle

or you can even toggle the effect like this

Upvotes: 2

Rituraj ratan
Rituraj ratan

Reputation: 10378

$("#lol").fadeOut(1000,function(){

$("#happy").fadeIn();
});

Upvotes: 0

David Byttow
David Byttow

Reputation: 271

Yes. Quite easy. Assuming #lol is visible and #happy is not. (You can use jQuery's show/hide to set that up).

$('#lol').fadeOut(function() {
  $('#happy').fadeIn();
});

Upvotes: 0

Related Questions