thomas
thomas

Reputation: 1174

Hiding a <div> and showing a new one in the same spot?

Lets say I have 2 divs, one is hidden, the other is showing. When a button is clicked, I want to use the jQuery fade effect to fade out one div and fade in the hidden div.

So -

<div id="part1">Hello</div>
<div id="part2" style="display: none">Hello2!</div>
<button id="btn1">Click here!</button>

and the JS -

$("#btn1").on("click", function(){
    $("#part1").fadeToggle();
    $("#part2").fadeToggle();
});

Now, this works, but as you can imagine what happens is that it first hides the 1st div, then shows the second div, and then immediately takes the second div up to the place where the previous div was located.

What can I do about this? I want them to stay in the same position (something like they have here http://kenwheeler.github.io/slick/ in their fade demo.)

Thanks!

Upvotes: 1

Views: 5721

Answers (6)

Gabriel Ferraz
Gabriel Ferraz

Reputation: 632

It seems that a lot of people answered this question correctly. I would like to add that you can also keep the div and just set the css opacity to 0 using the jQuery UI color animation.

I believe this is yet another option.

Upvotes: 2

Justin C
Justin C

Reputation: 333

At the time of writing, you have 4 answers that all seem to be correct solutions using CSS positioning. I noticed you have jQuery as a tag, so I thought I'd offer up a different solution.

Have you thought about not actually hiding the div, and replacing it with the other? For example, you could change the CSS class of the div with jQuery:

$('#part1').fadeOut(300, function() {
    $('#part1').addClass('part2');
    $('#part1').innerHTML('Hello2!');
    $('#part1').fadeIn(300, function(){});
});

Of course you should use a synchronous fade to make sure the class change happens while the div is hidden.

Upvotes: 2

jarbaugh
jarbaugh

Reputation: 533

You can do it with jQuery. Fade out the first div and fade in the second one in the callback. Like this: http://jsfiddle.net/D2Cw9/

$(".one").fadeOut(500, function() {
    $(".two").fadeIn(500, function() {
    });
});

Upvotes: 5

user3646269
user3646269

Reputation:

One solution would be using absolute positioning on both divs relative to their container.

#parts-container {
    position: relative;
}

#part1, #part2 {
    position: absolute;
    left: 0;
    top: 0;
}

Upvotes: 4

Streamside
Streamside

Reputation: 332

Use css position absolute to set them to the same position.

Upvotes: 2

DeadlyChambers
DeadlyChambers

Reputation: 5265

Try adding position absolute to both of them and wrapping them in a relative div

Upvotes: 1

Related Questions