Cwtch22
Cwtch22

Reputation: 79

How to make Div appear after 5 seconds javascript

So I created a Div and it will function as a button, I want it to remain invisible until 5 seconds have passed, then I would like the div to fade in. I have the code below but it doesn't work, any help?

Thanks!

Code:

Div ID for the button html:

<div id="button" onclick="window.open('home.html','home');" style="cursor: hand;">

Script:

<script>
$(function() {
$("#button").delay(2000).fadeIn(500);
});
</script>

html:

<title>Welcome to DayZ</title>
<link rel="shortcut icon" href="http://dayzgame.com/assets/img/favicon.ico">
<link rel="stylesheet" type="text/css" href="css/fadein.css">


<script src="scripts/fadein.js"></script>

<script>
$(function() {
$("#button").delay(5000).fadeIn(500);
});
</script>

Note: The above is just a snippet from my html file, not the full code.

Upvotes: 0

Views: 5371

Answers (3)

Josh Beam
Josh Beam

Reputation: 19772

//cache your selector
$button = $('button');

$button.hide();

var timeOut = setTimeout(function() {

    $button.fadeIn();

}, 5000);

That method hides the button on page load using JavaScript, and then uses a setTimeout object to cause it to wait 5 seconds before fading in (remember to cache your selectors for performance reasons, as well.)

For the sake of unobtrusive scripting, you might consider just using a simple CSS display: none instead of the hide() method.

For the sake of semantic HTML, I switched your #button to a button element, since your div looks and acts like a button element; either way the code will work, though.

Upvotes: 2

Captain John
Captain John

Reputation: 1891

You need to hide the div initially. display: none should needs to be an inline style:

<div id="button" onclick="window.open('home.html','home');" style="cursor: hand; display: none;">

Script:

<script>
$(function() {
    $("#button").delay(5000).fadeIn(500);
});
</script>

Jquery delay is expressed in milliseconds, therefore change the delay parameter to 5000.

Upvotes: 0

Tim B
Tim B

Reputation: 41188

You need to set the button to invisible before hand.

The style should be display:none or you can do an instant .fadeOut() (or .hide() as the other answer suggests) with duration 0, then the delay, then the fade in.

Upvotes: 0

Related Questions