Akshay Hazari
Akshay Hazari

Reputation: 3267

Fade in and fade out text at the same location

I want to write a code which can toggle two sentences fading in and fading out. But I want to toggle the sentences at the same location ie one text fades and the other starts coming in place of the first. In this case the sentences occur one below the other. Is there any way I can do this as in html content always comes one below the other.

This is the jquery script.

<script>
 $(document).ready(function(){
 $(function(){
       $("#hide1").hide();
       while(1)
      {
       $("#hide2").fadeOut(3000);
       $("#hide1").fadeIn(3000);
       $("#hide1").fadeOut(3000);
       $("#hide2").fadeIn(3000);
     }
 });
});
</script>

Html

<p id="hide1"> Hide 1 <p>
<p id="hide2"> Hide 2 <p>

Upvotes: 2

Views: 1204

Answers (3)

Balachandran
Balachandran

Reputation: 9637

Demo Try like this make the queue and animate

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

function hide1() {
    $("#hide2").fadeIn(3000);
    $("#hide2").fadeOut(3000, hide2);
}

function hide2() {

    $("#hide1").fadeIn(3000);
    $("#hide1").fadeOut(3000, hide1);
}
hide1();

OR Chaining

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

function hide1() {
    $("#hide2").fadeIn(3000).fadeOut(3000, hide2);
}

function hide2() {
    $("#hide1").fadeIn(3000).fadeOut(3000, hide1);
}
hide1();

This code would react dynamically, and it does not need any changes even if you want to apply this effect for more than two p elements

$("p").hide();

function test(elem) {
    elem.fadeIn(1000, function () {
        elem.fadeOut(1000, function () {
            test(elem.next('p').length ? elem.next('p') : $('p:first'));
        });
    });
}

test($('p:first'));

DEMO

Upvotes: 3

Chirag Bhatia - chirag64
Chirag Bhatia - chirag64

Reputation: 4516

Use a single paragraph tag and toggle the text within it while you try to fade it in and out.

$(document).ready(function(){
    $(function(){
        window.setInterval(function() {
            $("#hideorshow").fadeToggle(1000, "linear", function() {
                $("#hideorshow").text($("#hideorshow").text() === "Hide 1" ? "Hide 2" : "Hide 1");
                $("#hideorshow").fadeToggle(1000, "linear");
            });            
        }, 2000);
    });
});

Also, I would suggest you use fadeToggle() instead of fadeIn() and fadeOut().

Here is a working JSFiddle demo.

Upvotes: 1

urbz
urbz

Reputation: 2667

Try this:

setInterval(function () {
    $('#hide1').fadeOut(1000, function () {
        var $this = $(this);
        $this.text($this.text() == 'Hide 2' ? 'Hide 1' : 'Hide 2');
        $this.fadeIn(1000);
    });
}, 3000);

Toggle the text within the setInterval function.

Fiddle Demo

Upvotes: 1

Related Questions