Javascript - How to add a pause button in carousel? - php

I have found this script in Magento which is rotating images from a certain directory. This is working fine. But I need to add a "pause" button after the "1-6". I am not an expert on javascript so not sure how to do this. Can someone please help me with this?
The code:
<?php
$speed = 5000;//miliseconds
?>
<script type="text/javascript">
var timeoutID;
homeTileCount = 1;
$$('.home-tile-container img').each(function(e){
$(e).writeAttribute('id','home-tile-' + homeTileCount);
$(e).addClassName('home-tile');
homeTileCount++;
});
homeTileCount--;
var homeTileRemote = $$('.home-tile-remote')[0];
for (i=homeTileCount;i>=1;i--)
homeTileRemote.insert('<div id="home-tile-remote-'+i+'" class="overflow">'+i+'</div>');
function switchTile(n)
{
//console.log(n);
clearTimeout(timeoutID);
$$('.home-tile-container img').each(function(e){
e.removeClassName('home-tile-active');
});
$$('.home-tile-remote > div').each(function(e){
e.removeClassName('home-tile-remote-active');
});
$('home-tile-remote-'+n).addClassName('home-tile-remote-active');
$('home-tile-'+n).addClassName('home-tile-active');
next = n+1;
if (next > homeTileCount)
next = 1;
timeoutID = setTimeout('switchTile('+next+')', <?=$speed?>);
}
switchTile(1);
setTimeout('switchTile(2)', <?=$speed?>);
</script>
And this is how the carousel looks:

Maybe this:
<?php
$speed = 5000;//miliseconds
?>
<script type="text/javascript">
var paused=false;
var timeoutID;
homeTileCount = 1;
$$('.home-tile-container img').each(function(e){
$(e).writeAttribute('id','home-tile-' + homeTileCount);
$(e).addClassName('home-tile');
homeTileCount++;
});
homeTileCount--;
var homeTileRemote = $$('.home-tile-remote')[0];
for (i=homeTileCount;i>=1;i--)
homeTileRemote.insert('<div id="home-tile-remote-'+i+'" class="overflow">'+i+'</div>');
function switchTile(n)
{
if (!paused) {
//console.log(n);
clearTimeout(timeoutID);
$$('.home-tile-container img').each(function(e){
e.removeClassName('home-tile-active');
});
$$('.home-tile-remote > div').each(function(e){
e.removeClassName('home-tile-remote-active');
});
$('home-tile-remote-'+n).addClassName('home-tile-remote-active');
$('home-tile-'+n).addClassName('home-tile-active');
next = n+1;
if (next > homeTileCount)
next = 1;
timeoutID = setTimeout('switchTile('+next+')', <?=$speed?>);
}
}
switchTile(1);
setTimeout('switchTile(2)', <?=$speed?>);
</script>
<button type="button" onclick="paused=true;">Pause</button>

Related

How to dynamically create an instance of tinymce using javascript?

How to dynamically create an instance of tinymce using javascript? This is my code so far:
javascript:
$(function()
{
$("#onesnippet").click(function()
{
alert("One Snippet");
var idiv = document.getElementById('translations');
var newdiv = document.createElement('div');
newdiv.id = 10;
idiv.appendChild(newdiv);
var latestdiv = document.createElement('div')
latestdiv.id = 4;
newdiv.appendChild(latestdiv);
var textarea1 = document.createElement('textarea');
textarea1.id = "mceEditor3";
textarea1.className = "mceEditor";
latestdiv.appendChild(textarea1);
});
});
php file to include tinymce :
<script>
tinymce.init({mode : "specific_textareas", element : "mceEditor,mceEditor1,mceEditor2,mceEditor3", editor_selector : "mceEditor"});
</script>
You finish your code, and then add editor initiate code.
$(function()
{
$("#onesnippet").click(function()
{
alert("One Snippet");
var idiv = document.getElementById('translations');
var newdiv = document.createElement('div');
newdiv.id = 10;
idiv.appendChild(newdiv);
var latestdiv = document.createElement('div')
latestdiv.id = 4;
newdiv.appendChild(latestdiv);
var textarea1 = document.createElement('textarea');
textarea1.id = "mceEditor3";
textarea1.className = "mceEditor";
latestdiv.appendChild(textarea1);
tinymce.init({mode : "specific_textareas", element : "mceEditor,mceEditor1,mceEditor2,mceEditor3", editor_selector : "mceEditor"});
});
});

PHP with javascript code, live clock

Hey I would to create a live clock to put it on my website. So I wrote a simple php with JavaScript code for that, here is it:
<?php
Function d1() {
$time1 = Time();
$date1 = date("h:i:s A",$time1);
echo $date1;
}
?>
<script type="text/javascript">
window.onload = startInterval;
function startInterval() {
setInterval("startTime();",1000);
}
function startTime() {
document.getElementById('qwe').innerHTML = '<?php d1();?>';
}
</script>
<div id="qwe">test</div>
When run this code the output like "2:40:17 PM", the div refreshed every second but the problem is the time never changed.
Get the initial time you want to start your clock with from PHP:
<script>
var now = new Date(<?php echo time() * 1000 ?>);
function startInterval(){
setInterval('updateTime();', 1000);
}
startInterval();//start it right away
function updateTime(){
var nowMS = now.getTime();
nowMS += 1000;
now.setTime(nowMS);
var clock = document.getElementById('qwe');
if(clock){
clock.innerHTML = now.toTimeString();//adjust to suit
}
}
</script>
For formatting the date there's a zillion options (MDN Date API: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date)
<script type="text/javascript">
function timedMsg()
{
var t=setInterval("change_time();",1000);
}
function change_time()
{
var d = new Date();
var curr_hour = d.getHours();
var curr_min = d.getMinutes();
var curr_sec = d.getSeconds();
if(curr_hour > 12)
curr_hour = curr_hour - 12;
document.getElementById('Hour').innerHTML =curr_hour+':';
document.getElementById('Minut').innerHTML=curr_min+':';
document.getElementById('Second').innerHTML=curr_sec;
}
timedMsg();
</script>
<table>
<tr>
<td>Current time is :</td>
<td id="Hour" style="color:green;font-size:large;"></td>
<td id="Minut" style="color:green;font-size:x-large;"></td>
<td id="Second" style="color:red;font-size:xx-large;"></td>
<tr>
</table>
use this way to display time........
enjoy the above script
You can use ajax to refresh the time:
Example:
<?php
if(#$_GET["action"]=="getTime"){
$time1 = Time();
$date1 = date("h:i:s A",$time1);
echo $date1; // time output for ajax request
die();
}
?>
<div id="qwe">test</div>
<script type="text/javascript">
window.onload = startInterval;
function startInterval() {
setInterval("startTime();",1000);
}
function startTime() {
AX = new ajaxObject("?action=getTime", showTime)
AX.update(); // start Ajax Request
}
// CallBack
function showTime( data ){
document.getElementById('qwe').innerHTML = data;
}
</script>
<script type="text/javascript">
// Ajax Object - Constructor
function ajaxObject(url, callbackFunction) {
var that=this;
this.updating = false;
this.abort = function() {
if (that.updating) {
that.updating=false;
that.AJAX.abort();
that.AJAX=null;
}
};
this.update =
function(passData,postMethod) {
if (that.updating) { return false; }
that.AJAX = null;
if (window.XMLHttpRequest) {
that.AJAX=new XMLHttpRequest();
}else{
that.AJAX=new ActiveXObject("Microsoft.XMLHTTP");
}
if (that.AJAX==null) {
return false;
}else{
that.AJAX.onreadystatechange = function() {
if (that.AJAX.readyState==4) {
that.updating=false;
that.callback( that.AJAX.responseText, that.AJAX.status, that.AJAX.responseXML, that.AJAX.getAllResponseHeaders() );
that.AJAX=null;
}
};
that.updating = new Date();
if (/post/i.test(postMethod)) {
var uri=urlCall+(/\?/i.test(urlCall)?'&':'?')+'timestamp='+that.updating.getTime();
that.AJAX.open("POST", uri, true);
that.AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
that.AJAX.setRequestHeader("Content-Length", passData.length);
that.AJAX.send(passData);
}else{
var uri=urlCall+(/\?/i.test(urlCall)?'&':'?')+passData+'&timestamp='+(that.updating.getTime());
that.AJAX.open("GET", uri, true);
that.AJAX.send(null);
}
return true;
}
};
var urlCall = url;
this.callback = callbackFunction || function (){};
}
</script>

How To Save More fusion Charts On Server With Single Button

I am trying to save graphs on server side. i was succeeded up to save one graph. but i am unable to save more than one graph.
here i mentioned 2 graphs but nly one graph is going to save on server.
how it can be ?
my code is
<script type="text/javascript">
var totalCharts = 2;
function exportCharts(exportType)
{
for( var i = 0; i < totalCharts; i++ ) {
var num = i+1;
var id = "chart"+num+"Id";
exportchart(exportType,id);
}
}
function exportchart(exportType,id)
{
var chart = FusionCharts(id);
// Now, we proceed with exporting only if chart has finished rendering.
if (chart.hasRendered() != true)
{
alert("Please wait for the chart to finish rendering, before you can invoke exporting");
return;
}
// call exporting function
chart.exportChart( {exportFormat: exportType} );
}
</script>
<p align="center">
<input type="button" class="button" value="Export as PNG" onclick="exportCharts('PNG')" id="exportButtonPNG" />
</p>
<div >
<div id="average" style="text-align:center">Loading Chart... </div>
<div id="overall" style="text-align:center">Loading Chart... </div>
</div>
<script type="text/javascript" >
// Render the chart (See documentation for explanation of the codes below)
//echo renderChart("FusionCharts/MSColumn3D.swf", "", $strXML3, "average", 1100, 350);
var chart2 = new FusionCharts("FusionCharts/MSColumn3D.swf", "chart1Id", "600", "400", "0", "1");
chart2.setXMLUrl("average.xml");
chart2.render("average");
var chart1 = new FusionCharts("FusionCharts/MSColumn3D.swf", "chart2Id", "600", "400", "0", "1");
chart1.setXMLUrl("overall.xml");
chart1.render("overall");
</script>
<!-- Google Analytics Tracker Code Starts -->
<script type="text/javascript">
// analytics
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost
+ "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
if (typeof(_gat) == "object") {
var pageTracker = _gat._getTracker("UA-215295-3"); pageTracker._initData(); pageTracker._trackPageview();
}
</script>
How i can solve this?
You may need to chain the call to exportChart function of each chart you have.
var totalCharts = 2;
(function () {
var totalExported = 0,
exportType;
window.FC_Exported = function() {
exportchart();
};
window.exportchart = function(exportFormat) {
exportType = exportType || exportFormat || 'jpg';
totalExported++ ;
var chart = FusionCharts("chart" + totalExported + "Id");
if (totalExported > totalCharts) {
return;
}
if (chart.hasRendered() != true) {
alert("Please wait for the chart to finish rendering, before you can invoke exporting");
}
// call exporting function
chart.exportChart( {exportFormat: exportType} );
};
}());

How to get total value on dynamic value?

I have form like this :
<input type='hidden' name='seq' id='idseq' value='1' />
<div id='add_field' class='locbutton'><a href='#' title='Add'>Add</a></div>
<div id='remove_field' class='locbutton2'><a href='#' title='Delete'>Delete</a></div>
<div id="idcover">
1.<br />
<div class="group">
<div class="satu"><input type='text' name='score[1][]' id='score[1][]'></div>
<div class="dua"><input type='text' name='weight[1][]' id='weight[1][]'> %</div>
<div class="tiga"><input type='text' name='weightscore[1][]' id='weightscore[1][]'
disabled></div>
</div>
</div>
<br /><br />
<div id='idtotalcover' class='totalcover'>
Total <div class='total'><input type='text' name='total' id='idtotal' disabled /></div>
</div>
This is the jquery script:
<script type="text/javascript">
$(document).ready(
function ()
{
$("input[id^=score],input[id^=weight]").bind("keyup", recalc);
recalc();
var counter = $("#idseq").val();
$("#add_field").click(function ()
{
counter++;
$.ajax({
url: 'addinput.php',
dataType: "html",
data: "count="+counter,
success: function(data)
{
$('#idcover').append(data);
$('.dua input').keyup(function()
{
var $duaInput = $(this);
var weight=$duaInput.val();
var score=$duaInput.closest(".group").find('.satu input').val();
$.ajax({
url: "cekweightscore.php",
data: "score="+score+"&weight="+weight,
success:
function(data)
{
$duaInput.closest(".group").find('.tiga input').val(data);
}//success
});//ajax
});
}//success
});//ajax
});
});
function recalc()
{
var a=$("input[id^=score]");
var b=$("input[id^=weight]");
$("[id^=weightscore]").calc("(score * weight)/100",{score: a,weight: b},
function (s)
{
return s.toFixed(2);
},
function ($this){
//function($("[id^=weightscore]")){
// sum the total of the $("[id^=total_item]") selector
//alert($this);
//var sum = $this.sum();
var sum=$this.sum();
$("#idtotal").val(sum.toFixed(2));
}
);
}
</script>
This is the php code:
<?
$count=$_GET['count'];
echo"
<br>
$count
<div class='group' >
<div class='satu'>
<input type='text' name='score[$count][]' id='score[$count][]'>
</div>
<div class='dua'>
<input type='text' name='weight[$count][]' id='weight[$count][]'> %
</div>
<div class='tiga'>
<input type='text' name='weightscore[$count][]' id='weightscore[$count][]' disabled>
</div>
</div>";
?>
When I click the Add button, i cant get value on new form so that the new form cannot be calculated. What can i do to get total value on dynamic value ?
I remember reading this exact same question yesterday and I still have no idea of what you're trying to do.
Why are you adding inputs through AJAX instead of creating them in Javascript from the beginning? AJAX calls are expensive and are recommended to be used when you need to update/retrieve values from the server.
Why are you trying to do your calculations on the server side anyway? If you're dealing with dynamic input, you should be doing the calculations client side, then update the server when you're done.
Why do you use obscure name/id attribute values?
Anyway,
I created this example, it contains two different solutions, one with a ul and a table. Hopefully, the example matches what you're trying to do and might give you some insight.
I use a timer to update simulated server data. The timer is set to the variable update_wait. The other dynamic calculations are done client side.
I'll post the Javascript code as well, in case you don't like to fiddle
Example | Javascript
var update_server_timer = null,
update_wait = 1000; //ms
var decimals = 3;
/**********************
List solution
**********************/
function CreateListRow(){
var eLi = document.createElement("li"),
eScore = document.createElement("div"),
eWeight = document.createElement("div"),
eWeightScore = document.createElement("div");
var next_id = $("#cover li:not(.total)").length + 1
eScore.className = "score";
eWeight.className = "weight";
eWeightScore.className = "weightscore";
//Score element
var eScoreInput = document.createElement("input");
eScoreInput.type = "text";
eScoreInput.name = "score_"+next_id;
eScoreInput.id = "score_"+next_id;
eScore.appendChild(eScoreInput);
//Weight element
var eWeightInput = document.createElement("input");
eWeightInput.type = "text";
eWeightInput.name = "weight_"+next_id;
eWeightInput.id = "weight_"+next_id;
var eWeightPerc = document.createElement("div");
eWeightPerc.className = "extra";
eWeightPerc.innerHTML = "%";
eWeight.appendChild(eWeightInput);
eWeight.appendChild(eWeightPerc);
//Weightscore element
var eWeightScoreInput = document.createElement("input");
eWeightScoreInput.type = "text";
eWeightScoreInput.name = "weight_"+next_id;
eWeightScoreInput.id = "weight_"+next_id;
eWeightScore.appendChild(eWeightScoreInput);
$(eScore).keyup(function(){
CalculateListRow($(this).closest("li"));
});
$(eWeight).keyup(function(){
CalculateListRow($(this).closest("li"));
});
//item element
eLi.appendChild(eScore);
eLi.appendChild(eWeight);
eLi.appendChild(eWeightScore);
return eLi;
}
function CalculateListRowTotal(){
var fTotal = 0;
$("#cover li:not(.total) div:nth-child(3) input").each(function(){
var fVal = parseFloat($(this).val());
if(isNaN(fVal)) fVal = 0;
fTotal += fVal;
});
fTotal = parseFloat(fTotal.toFixed(decimals));
$("#cover li.total div input").val(fTotal);
//Update server variables here
RestartUpdateServerTimer();
}
function CalculateListRow($Li){
var fScore = parseFloat($("div.score input", $Li).val()),
fWeight = parseFloat($("div.weight input", $Li).val())/100,
fRes = (fScore*fWeight);
if(isNaN(fRes)) fRes = 0.00;
$("div.weightscore input", $Li).val(parseFloat(fRes.toFixed(decimals)));
CalculateListRowTotal();
}
$("#cover li div.weight input, #cover li div.score input").keyup(function(){
CalculateListRow($(this).closest("li"));
});
function AddListRow(){
$("#cover li.total").before(CreateListRow());
RestartUpdateServerTimer();
}
function RemoveListRow(){
$("#cover li.total").prev().remove();
CalculateListRowTotal();
}
$(".left_container .menu .add").click(function(){ AddListRow(); });
$(".left_container .menu .rem").click(function(){ RemoveListRow(); });
/**********************
Table solution
**********************/
function CreateTableRow(){
var eTr = document.createElement("tr"),
eTds = [document.createElement("td"),
document.createElement("td"),
document.createElement("td")];
var next_id = $("#cover2 tbody tr").length + 1;
$(eTds[0]).append(function(){
var eInput = document.createElement("input");
eInput.type = "text";
eInput.name = eInput.id = "score_"+next_id;
$(eInput).keyup(function(){
CalculateTableRow($(this).closest("tr"));
});
return eInput;
});
$(eTds[1]).append(function(){
var eRelativeFix = document.createElement("div"),
eInput = document.createElement("input"),
eExtra = document.createElement("div");
eRelativeFix.className = "relative_fix";
eInput.type = "text";
eInput.name = eInput.id = "weight_"+next_id;
eExtra.innerHTML = "%";
eExtra.className = "extra";
eRelativeFix.appendChild(eInput);
eRelativeFix.appendChild(eExtra);
$(eInput).keyup(function(){
CalculateTableRow($(this).closest("tr"));
});
return eRelativeFix;
});
$(eTds[2]).append(function(){
var eInput = document.createElement("input");
eInput.type = "text";
eInput.name = eInput.id = "weightscore_"+next_id;
return eInput;
});
for(i = 0; i < eTds.length; i++){
eTr.appendChild(eTds[i]);
}
return eTr;
}
function CalculateTableRowTotals(){
var $rows = $("#cover2 tbody tr"),
$totals = $("#cover2 tfoot tr th");
var fTotal = [];
//Each row
$rows.each(function(){
var $columns = $("td", this);
//Each column
$columns.each(function(i, e){
var fVal = parseFloat($("input", e).val());
if(isNaN(fVal)) fVal = 0;
if(isNaN(fTotal[i])) fTotal[i] = 0;
fTotal[i] += fVal;
});
});
for(i = 0; i < fTotal.length; i++){
fTotal[i] = parseFloat(fTotal[i].toFixed(decimals));
}
fTotal[1] = (fTotal[2]/fTotal[0]*100).toFixed(decimals)+"%";
fTotal[2] = parseFloat(fTotal[2].toFixed(decimals));
$totals.each(function(i, e){
$(this).text(fTotal[i]);
});
//Update server variables here
RestartUpdateServerTimer();
}
function CalculateTableRow($Tr){
var fScore = parseFloat($("td:nth-child(1) input", $Tr).val()),
fWeight = parseFloat($("td:nth-child(2) input", $Tr).val())/100,
fRes = (fScore*fWeight);
if(isNaN(fRes)) fRes = 0.00;
$("td:nth-child(3) input", $Tr).val(parseFloat(fRes.toFixed(decimals)));
CalculateTableRowTotals();
}
function AddTableRow(){
if($("#cover2 tbody tr").length == 0){
$("#cover2 tbody").append(CreateTableRow());
}else{
$("#cover2 tbody tr:last-child").after(CreateTableRow());
}
RestartUpdateServerTimer();
}
function RemoveTableRow(){
$("#cover2 tbody tr:last-child").remove();
CalculateTableRowTotals();
}
$(".right_container .menu .add").click(function(){ AddTableRow(); });
$(".right_container .menu .rem").click(function(){ RemoveTableRow(); });
$("#cover2 tbody tr td:nth-child(1) input, #cover2 tbody tr td:nth-child(2) input").keyup(function(){
CalculateTableRow($(this).closest("tr"));
});
/**********************
Server data
- Simulates the data on the server,
- whether it be in a SQL server or session data
**********************/
var ServerData = {
List: {
Count: 3,
Total: 5.50
},
Table: {
Count: 3,
Totals: [65, 8.46, 5.50]
}
};
function UpdateServerData(){
//List
var ListCount = $("#cover li:not(.total)").length,
ListTotal = $("#cover li.total input").val();
//Table
var TableCount = $("#cover2 tbody tr").length,
TableTotals = [];
$("#cover2 tfoot th").each(function(i, e){
TableTotals[i] = parseFloat($(this).text());
});
var data = {
json: JSON.stringify({
List: {
Count: ListCount,
Total: ListTotal
},
Table: {
Count: TableCount,
Totals: TableTotals
}
})
}
//Update
$.ajax({
url: "/echo/json/",
data: data,
dataType: "json",
type:"POST",
success: function(response){
ServerData.List = response.List;
ServerData.Table = response.Table;
var displist = "Server data<h1>List</h1><ul><li>Count: "+ServerData.List.Count+"</li><li>Total: "+ServerData.List.Total+"</li></ul>",
disptable = "<h1>Table</h1><ul><li>Count: "+ServerData.Table.Count+"</li>";
for(i=0; i<ServerData.Table.Totals.length; i++)
disptable += "<li>Total "+i+": "+ServerData.Table.Totals[i]+"</li>";
disptable += "</ul>";
$("#server_data").html(displist+"<br />"+disptable).effect("highlight");
}
});
}
function RestartUpdateServerTimer(){
if(update_server_timer != null) clearTimeout(update_server_timer);
update_server_timer = setTimeout(function(){
UpdateServerData()
}, update_wait);
}
UpdateServerData();
Update
Since you have a hard time grasping the concept, here's a copy paste solution that will work for you without having to use AJAX. I would like to point out that your HTML markup and general coding is a total mess...
Example | Code
<script type="text/javascript">
$(document).ready(function(){
function CreateInput(){
var $group = $("<div>"),
$score = $("<div>"),
$weight = $("<div>"),
$weightscore = $("<div>");
var group_count = $("div.group").length+1;
$group.addClass("group");
$score.addClass("satu");
$weight.addClass("dua");
$weightscore.addClass("tiga");
var $input_score = $("<input>"),
$input_weight = $("<input>"),
$input_weightscore = $("<input>")
$input_score
.attr("name", "score["+group_count+"][]")
.attr("type", "text")
.attr("id", "score["+group_count+"][]");
$input_weight
.attr("name", "weight["+group_count+"][]")
.attr("type", "text")
.attr("id", "weight["+group_count+"][]");
$input_weightscore
.attr("name", "weightscore["+group_count+"][]")
.attr("type", "text")
.attr("id", "weightscore["+group_count+"][]")
.attr("disabled", true);
$input_score.keyup(function(){
CalculateGroup($(this).parents(".group"));
});
$input_weight.keyup(function(){
CalculateGroup($(this).parents(".group"));
});
$score.append($input_score);
$weight.append($input_weight);
$weightscore.append($input_weightscore);
$group.append($score)
.append($weight)
.append($weightscore);
return $group;
}
function CalculateGroup($group){
var fScore = parseFloat($(".satu input", $group).val()),
fWeight = parseFloat($(".dua input", $group).val()),
fWeightScore = parseFloat((fScore*(fWeight/100)).toFixed(2));
if(isNaN(fWeightScore)) fWeightScore = 0;
$(".tiga input", $group).val(fWeightScore);
CalculateTotal();
}
function CalculateTotal(){
var fWeightScoreTotal = 0;
$("#idcover div.group div.tiga input").each(function(){
var fTotal = parseFloat(parseFloat($(this).val()).toFixed(2));
if(isNaN(fTotal)) fTotal = 0;
fWeightScoreTotal += fTotal;
});
fWeightScoreTotal = parseFloat(fWeightScoreTotal.toFixed(2));
$("#idtotalcover div.total input").val(fWeightScoreTotal);
}
$(".satu input, .dua input").keyup(function(){
CalculateGroup($(this).parents(".group"));
});
$("#add_field a").click(function(e){
$("#idcover").append(CreateInput());
e.preventDefault();
});
$("#remove_field a").click(function(e){
$("#idcover div.group:last-child").remove();
CalculateTotal();
e.preventDefault();
});
});
</script>

Show Redirecting In.. CountDown Timer PHP

I have this code so far that redirects the user after 5 seconds to the correct URL:
<?php
$url = $_GET['url'];
header("refresh:5;url=$url");
include('ads.php');
?>
Please could you tell me how i could display a countdown timer saying Redirecting In.. with .. being the amount of seconds left. I am new to web development so all code will be helpful!
<script type="text/javascript">
(function () {
var timeLeft = 5,
cinterval;
var timeDec = function (){
timeLeft--;
document.getElementById('countdown').innerHTML = timeLeft;
if(timeLeft === 0){
clearInterval(cinterval);
}
};
cinterval = setInterval(timeDec, 1000);
})();
</script>
Redirecting in <span id="countdown">5</span>.
You can try this.
As this is a common beginner question; I just wanted to highlight that for best practise setInterval should, and can usually be avoided by using setTimeout recursively within a function.
For example:
var timer = 5,
el = document.getElementById('countdown');
(function t_minus() {
'use strict';
el.innerHTML = timer--;
if (timer >= 0) {
setTimeout(function () {
t_minus();
}, 1000);
} else {
// do stuff, countdown has finished.
}
}());
Excellent code by Kyle. I have modified the timer with a pause and resume button.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
var time_left = 50;
var cinterval;
var timestatus=1;
function time_dec(){
time_left--;
document.getElementById('countdown').innerHTML = time_left;
if(time_left == 0){
clearInterval(cinterval);
}
}
function resumetime()
{
//time_left = 50;
clearInterval(cinterval);
cinterval = setInterval('time_dec()', 1000);
}
function defaultstart()
{
time_left = 50;
clearInterval(cinterval);
cinterval = setInterval('time_dec()', 1000);
}
function stopstarttime()
{
if(timestatus==1)
{
clearInterval(cinterval);
document.getElementById('stopbutton').value="Start";
timestatus=0;
}
else
{
clearInterval(cinterval);
cinterval = setInterval('time_dec()', 1000);
document.getElementById('stopbutton').value="Stop";
timestatus=1;
}
}
defaultstart();
</SCRIPT>
</HEAD>
<body>
Redirecting In <span id="countdown">50</span>.
<INPUT TYPE="button" value="stop" id="stopbutton" onclick="stopstarttime()">
</body>
</HTML>
Here is my take on it, without variables outside of the function. Depends on jQuery.
function count_down_to_action(seconds, do_action, elem_selector)
{
seconds = typeof seconds !== 'undefined' ? seconds : 10;
$(elem_selector).text(seconds)
var interval_id = setInterval(function(){
if (seconds <= 0)
{
clearInterval(interval_id);
if (typeof do_action === 'function')
do_action();
}
else
$(elem_selector).text(--seconds);
},1000)
}
​
Here is an example using it http://jsfiddle.net/VJT9d/

Categories