user1067282
user1067282

Reputation: 1

How do i fade one div out and fade one in with a click of one element? HTML

I want a paragraph of text to fade out, and another one to take its place when I click on an href in my code.

HTML

<a href="#" id="switch"">Espanol</a>

<p class="english">This is an english paragraph</p>
<p class="spanish">Se es la espanol pargrafio</p>

CSS

.spanish {
    display: none;  
}
.english {
    display: block; 
}

Jquery

$("#switch").click(function(){
    $("p.spanish").show();
    $("p.english").hide();
})

Now all I want is one to disappear and another to appear in its place with one click, but this code is not working, please help!

Upvotes: 0

Views: 718

Answers (4)

fardjad
fardjad

Reputation: 20394

Remove the extra quote on your markup after <a href="#" id="switch" and use something like this:

$("#switch").click(function() {
    var toHide = $("p." + ($('p.english').css('display') == 'none' ? 'spanish' : 'english'));
    $(toHide).fadeOut();

    toHide.next().css("margin-top", -1 * toHide.height());
    toHide.next().fadeIn(function() {
        toHide.next().css("margin-top", "auto");
        toHide.insertAfter(toHide.next());
    });

    return false;
});

See this demo.

Upvotes: 1

David Thomas
David Thomas

Reputation: 253308

You can use a callback within the hide() or, as in the example fadeOut() function:

$('#switch').click(
    function(e){
        e.preventDefault();
        $('p.english').fadeOut(
            function(){
                $('p.spanish').fadeIn();
            });
    });

JS Fiddle demo.


Edited with a slightly improved version of the above:

$('#switch').click(
    function(e){
        e.preventDefault();
        $('p.english, p.spanish').fadeToggle(400);
        $(this).text(
            function(){
                if ($(this).text() == 'English'){
                    $(this).text('Espanol');
                }
                else if ($(this).text() == 'Espanol'){
                    $(this).text('English');
                }
            });
    });

JS Fiddle demo.

References:

Upvotes: 2

Tomalak
Tomalak

Reputation: 338158

HTML

<a href="#" id="switch"">Español</a>
<a class="english">This is an english paragraph</p>
<p class="spanish hide">Se es la español pargrafio</p>

CSS

.hide {
  display: none;  
}

jQuery

$("#switch").click(function(){
  $("p.spanish, p.english").toggleClass("hide");
  $(this).text( $("p.spanish").is(":visible") ? "English" : "Español" );
});

Upvotes: 1

BronzeByte
BronzeByte

Reputation: 725

I don't think it fixes the problem, but replace id="switch"" with id="switch"

Upvotes: 0

Related Questions