JQuery; click to show html content and countdown followed by additional content
I wanted to create a link that would show the content before showing the direct link on my forum.
- Show download link.
- After clicking on it, html content is displayed with a 5 second countdown below
- When the countdown is over, it shows a direct link.
I've tried the following code:
$("button").click(function() {
$(function() {
var count = 10;
countdown = setInterval(function() {
$("p.countdown").html(count + " seconds remaining!").show("slow");
if (count == 0) {
$("p.new").show("slow");
}
count--;
}, 1000);
});
});
source to share
How about a magic function?
To talk about @ Bradley Foster's answer, calling multiple times is setTimeout
not reliable. setTimeout
will stop if your browser is lagging, so with four different points, you're not sure the order will be correct. Attachment setTimeout
as I show which is better.
$('#button').click(function() {
var seconds = 5, // Declare some variables for reuse
el = $('#some_link')
el.text(seconds) // Put it a five!
// Name your function so that you can call it later
setTimeout(function countdown() {
// Your countdown is already at 5, so decrement it
// Remember that you've already waited for 1000ms before reaching this line the first time
seconds--
el.text(seconds) // Set the new time left
// If the countdown is not over, recall this function after 1000ms
if (seconds > 0) {
setTimeout(countdown, 1000)
}
// If it is over, display the link
// Note that js will stop there and not try to call itself another time as it would with setInterval()
else {
el.html('<a href="link">Download</a>')
}
}, 1000)
})
By the way, in your question, when you do $(function() {...
, you actually do $(document).ready(function() {...
. I guess this is not what you wanted :)
Jsfiddle here: http://jsfiddle.net/Ralt/kTbcm/
source to share
You can do something like this:
HTML:
<button>Download</button>
<p class="countdown" />
<p class="link">
<a href="www.stackoverflow.com">StackOverflow</a>
</p>
CSS
p { display: none; padding: 50px; border: solid 1px black; }
p.countdown { color: red; font-size: 24px; }
JQuery
var $countdown = $("p.countdown"),
$link = $("p.link"),
$button = $("button");
$button.click(function() {
$countdown.hide(0);
$link.hide(0);
var count = 10,
countdown = setInterval(function() {
$countdown.html(count + " seconds remaining!").show("slow");
if (count == 0) {
$countdown.hide(0);
$link.show("slow");
clearInterval(countdown);
}
count--;
}, 1000);
});
source to share
function countdownfunction() {
$('#some_link').innerHTML = "5";
$('#some_link').innerHTML = setTimeout("4",1000);
$('#some_link').innerHTML = setTimeout("3",1000);
$('#some_link').innerHTML = setTimeout("2",1000);
$('#some_link').innerHTML = setTimeout("1",1000);
$('#some_link').innerHTML = '<a href="newlink.php">download now</a>;
};
$('#some_link').click( countdownfunction() );
source to share