Reputation:
I am trying to implement a countdown timer into my page to show when the page will be redirect to google.com. So far i have create a button but it will only start counting when i clicked it. Is it possible to make the button auto start countdown when i access to that page?
<button id="myButton" class="butstyle" style="float:right">Click To Redirect</button>
<script>
var counter = 10;
$('.butstyle').on('click',function(e){
e.preventDefault();
e.stopPropagation();
if($(this).hasClass('butstyle')){
$('.butstyle').text('You will be redirected in: 10 seconds');
$(this).removeClass().addClass('butAfter');
var int = setInterval(function() {
counter--;
$('.butAfter').text('You will be redirected in: '+counter+' seconds');
if (counter == 0) {
clearInterval(int);
counter = 10;
window.location.href = "https://www.google.com";
//do your next action here:
}
}, 1000);
}
});
</script>
Upvotes: 1
Views: 264
Reputation: 5488
Use this. This will automatically clicks on you button with this part of code
$(document).ready(function() {
$(".butAfter").trigger("click");
});
And Counter starts.
Final code:
$(document).on("click", ".butAfter", function(e) {
e.preventDefault();
e.stopPropagation();
if ($(this).hasClass('butstyle')) {
$('.butstyle').text('You will be redirected in: 10 seconds');
$(this).removeClass().addClass('butAfter');
var int = setInterval(function() {
counter--;
$('.butAfter').text('You will be redirected in: ' + counter + ' seconds');
if (counter == 0) {
clearInterval(int);
counter = 10;
window.location.href = "https://www.google.com";
//do your next action here:
}
}, 1000);
}
});
$(document).ready(function() {
$(".butAfter").trigger("click");
});
var counter = 10;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="myButton" class="butstyle butAfter" style="float:right">Click To Redirect</button>
Upvotes: 1
Reputation: 3454
You can switch your button on click function with document ready like this:
$( document ).ready(function() {
// Put relevant code here
}
Upvotes: 1