Shihan Khan
Shihan Khan

Reputation: 2188

Show div for a moment then switch to another div in jquery

I'm trying to make an animation with jQuery 1.9.1 where I want to show a div for a short moment then switch it with the defualt div at button click. So far I've tried using show() & hide() method. But nothing is working. Here are my codes,

<script>
    $(document).ready(function (){
        $('#btnChange').click(function () {
            $('#red').hide();
            $('#blue').show().delay(1500).hide();
            $('#red').show();
        });
    });
</script>

JSFiddle Demo Here

How can I show a div for a moment and after that switch it with the default div #red at button click? Neec this help badly. Thanks!

Upvotes: 1

Views: 195

Answers (5)

pravid
pravid

Reputation: 729

try this code

$(document).ready(function (){
$('#btnChange').click(function () {

    $('#red').fadeOut(500);
    $('#blue').fadeIn(500, function() {
        $('#blue').delay(3000).hide();
        $('#red').delay(5000).show();
    });
  });
});

Upvotes: 0

A. Wolff
A. Wolff

Reputation: 74420

If you set duration for .hide( [duration ] [, complete ] ) method, it'll be placed in fx queue and so delay would work:

You should stop() any previous animation to better handling multiple clicks btw

$(document).ready(function (){
    $('#btnChange').click(function () {
        $('#red').hide();
        $('#blue')/*.stop()*/.show().delay(1500).hide(0);
        $('#red').show();
    });
});

-jsFiddle-

With .stop():

-jsFiddle-

Upvotes: 2

yuk
yuk

Reputation: 933

$('#blue').show('slow', function(){
        $('#blue').hide();              
});

http://jsfiddle.net/f87zp3rg/3/

Upvotes: 0

Seth McClaine
Seth McClaine

Reputation: 10030

You showing your #red again to fast.. use setTimeout

window.setTimeout(code, [delay]);

$(document).ready(function (){
    $('#btnChange').click(function () {
        $('#red').hide();
        $('#blue').show();
        window.setTimeout(function() { 
          $('#red').show(); 
          $('#blue').hide()
        },1500);
    });
});

JSFidde: http://jsfiddle.net/f87zp3rg/4/

Upvotes: 0

DavidDomain
DavidDomain

Reputation: 15293

Use a simple setTimeout

$(document).ready(function (){
  $('#btnChange').click(function () {
    $('#red').hide();
    $('#blue').show();
    setTimeout(function() {
      $('#blue').hide();
      $('#red').show();
    }, 1500);
  });
});
#red{
    position: absolute;
	width: 178px;
	height: 124px;
    background-color: red;
	overflow: hidden;
}
#blue{
    position: absolute;
	width: 178px;
	height: 124px;
    background-color: blue;
	overflow: hidden;
    display: none;
}
#btnChange{
    position: absolute;
    top: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="red"></div>
<div id="blue"></div>
<button id="btnChange">Change!</button>

Upvotes: 1

Related Questions