Time countdown in an tooltip - javascript

This is my countdown script :
<script type='text/javascript'>
function cronometru(timp_ramas) {
Ore = Math.floor(timp_ramas / 3600);
minute = Math.floor((timp_ramas - Ore * 3600) / 60);
secunde = timp_ramas - minute * 60 - Ore * 3600;
if (Ore < 10){ Ore = "0"+ Ore; }
if (minute < 10){ minute = "0" + minute; }
if (secunde < 10){ secunde = "0" + secunde; }
if (timp_ramas > 0) {
timp_ramas--;
document.getElementById("timp").innerHTML = Ore + ':' + minute + ':' + secunde;
setTimeout("cronometru("+timp_ramas+")", 1000);
} else {
document.getElementById("timp").innerHTML = "Focul s-a stins !";
}
}
$timp_ramas = $citeste['timp_ramas_pentru_foc'] - time(); // this is the function that retrives the actual time from an database.
I use this "wz_tooltip.js" for the tooltip events.
<script type="text/javascript" src="wz_tooltip.js"></script>
When i try to put to show my conuntdown in the tooltip the tooltip goes black and show only the message before or after the countdown position ('Timp ramas :')
Example :
if ($citeste["timp_ramas_pentru_foc"] > 0)
{
echo "
<a onmouseover=
\"Tip('Timp ramas : <span id=timp></span> ')\"
onmouseout=\"UnTip()\">
<img src='img/skiluri/fire_yes.png'/> </a>
";
}
I found a way to make the code to work but the timer will be shown in 2 places in the same time. I want only to read it when i move the cursor on some picture / text and the tooltip apears.
Example of working code with 2 views in the same time :
$timp_ramas = $citeste['timp_ramas_pentru_foc'] - time();
?>
<script type='text/javascript'>
function cronometru(timp_ramas) {
Ore = Math.floor(timp_ramas / 3600);
minute = Math.floor((timp_ramas - Ore * 3600) / 60);
secunde = timp_ramas - minute * 60 - Ore * 3600;
if (Ore < 10){ Ore = "0"+ Ore; }
if (minute < 10){ minute = "0" + minute; }
if (secunde < 10){ secunde = "0" + secunde; }
if (timp_ramas > 0) {
timp_ramas--;
document.getElementById("timp").innerHTML = Ore + ':' + minute + ':' + secunde;
setTimeout("cronometru("+timp_ramas+")", 1000);
} else {
document.getElementById("timp").innerHTML = "Focul s-a stins !";
}
}
<script src="js/meniu_dreapta/iconmenu.js"></script>
<body>
<script type="text/javascript" src="js/tooltip/wz_tooltip.js"></script>
<span id='timp'></span> <?php echo "<script type='text/javascript'>cronometru(".$timp_ramas.")</script>"; ?>
<?php
echo '
<html>
<ul id="myiconmenu" class="iconmenu"> ';
if ($citeste["timp_ramas_pentru_foc"] > 0)
{
echo "
<a onmouseover=
\"Tip('Timp ramas : <span id=timp></span> ')\"
onmouseout=\"UnTip()\">
<img src='img/skiluri/fire_yes.png'/> </a>
";
}
Thank you.

Related

How to render a Dynamic Timer (Countdown) With JavaScript and Datatable's Render?

I want to render a Countdown for a different time for different Products I use MVC EntityFrameWork and for client-side jQuery and JavaScript.
When You datatable's render section so you find a JavaScript SetInterval function to make it dynamic but it didn't work When I only use the JavaScript method SetTime (made by self)
The SetTimer Function gets the remaining time for products and I want This function to run again and again every second to make this dynamic
Is there any other way to perform this Action?
table = $('#ProductTable').DataTable({
"ajax": {
"url": "/api/product/",
"type": "GET",
"dataSrc": ""
},
"columns": [
{
"data": "id",
render: function (data, type, Product) {
debugger;
return "<div id='ProductCover'> <div id='Product-img-div'> <img src='/Content/Images/" + Product.images + "' width='200px'></div> <div style='margin-right: 50px;'> Product Name:<h5> " + Product.productName + " <h5> Product Descrption: <h5> " + Product.description + "</h5> </div> <div class='countdown'> End Time: <span class='clock'> " + **setInterval(SetTimer(Product.endBidDate),1000)** +" </span > </div > <br><div style='margin-left:50px;'> Current Highest Amount:<h5>" + Product.highestAmount + " </h5> </div> </div> <button type='button' class='btn btn-primary' onclick='BidModal(" + Product.id + ")'>new Bids </button> <button class='btn btn-primary' data-toggle='modal' data-target='#BuyerQuyerModal' data-whatever='#mdo' onclick='Select(" + Product.id + ")'>Ask Seller</button> </div> ";
}
}
]
})
}
This Script finds the remaining time with the End Date of the Product Sale and I call this function in HTML (datatable's render section) How can I call this with SetInterval so I can time goes in backward
function setTimer(endTimes) {
var endTime = endTimes;
timerrrr = endTime
endTime = (Date.parse(endTime) / 1000);
var now = new Date();
now = (Date.parse(now) / 1000);
var timeLeft = endTime - now;
var days = Math.floor(timeLeft / 86400);
var hours = Math.floor((timeLeft - (days * 86400)) / 3600);
var minutes = Math.floor((timeLeft - (days * 86400) - (hours * 3600)) / 60);
var seconds = Math.floor((timeLeft - (days * 86400) - (hours * 3600) - (minutes * 60)));
if (hours < "10") { hours = "0" + hours; }
if (minutes < "10") { minutes = "0" + minutes; }
if (seconds < "10") { seconds = "0" + seconds; }
return `${days} : ${hours} : ${minutes} : ${seconds}`;
}
I would place the setInterval function in the DataTable initComplete option, instead of in a column renderer:
initComplete: function () {
setInterval(function () {
doCountdowns();
}, 1000);
}
Here is a very basic runnable demo showing that aproach:
function doCountdowns() {
$( '.endtime' ).each(function( index ) {
doCountdown( this ); // a td node
});
}
function doCountdown( node ) {
let endTime = Date.parse( $( node ).html() ) / 1000;
let now = (Date.parse(new Date()) / 1000);
let timeLeft = endTime - now;
let days = Math.floor(timeLeft / 86400);
let hours = Math.floor((timeLeft - (days * 86400)) / 3600);
let minutes = Math.floor((timeLeft - (days * 86400) - (hours * 3600)) / 60);
let seconds = Math.floor((timeLeft - (days * 86400) - (hours * 3600) - (minutes * 60)));
if (hours < "10") { hours = "0" + hours; }
if (minutes < "10") { minutes = "0" + minutes; }
if (seconds < "10") { seconds = "0" + seconds; }
$( node ).next("td").html( `${days} : ${hours} : ${minutes} : ${seconds}` );
}
$(document).ready(function() {
$('#example').DataTable( {
initComplete: function () {
setInterval(function () {
doCountdowns();
}, 1000);
}
} );
} );
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">
</head>
<body>
<div style="margin: 20px;">
<table id="example" class="display dataTable cell-border" style="width:100%">
<thead>
<tr>
<th>Product ID</th>
<th>End Bid Date</th>
<th>Time Remaining</th>
</tr>
</thead>
<tbody>
<tr>
<td>123</td>
<td class="endtime">2022-12-04 13:44:35</td>
<td></td>
</tr>
<tr>
<td>456</td>
<td class="endtime">2022-11-07 06:21:12</td>
<td></td>
</tr>
<tr>
<td>789</td>
<td class="endtime">2022-10-04 17:23:00</td>
<td></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
You may need to adjust this to account for your specific data & formatting - and the fact that you are using an Ajax data source - but the approach should be the same.
As an enhancement: You may also need some logic to handle the data when the deadline is reached, otherwise you will get incorrect data displayed.

Coundown Timer Inside ForEach Loop Php

I am trying to Show a Countdown Timer Inside Foreach loop for every record in PHP Codeigniter Framework, It is basically showing Datediff between current date and mysql database date value as how many days left, Below is my code.Problem is it is showing countdown timer for single record only not for every record i need
<?php foreach ($my_courses as $my_course):
$course_details = $this->crud_model->get_course_by_id($my_course['course_id'])->row_array();
<!-- countdown timer-->
<?php if ($course_details['is_onlineclass']==='Yes'): ?>
<span style="display:inline-block;font-size:12px;font-color:crimson;"><?php
$t=$course_details['live_class_schedule_time'];
//time difference in seconds for coundown timer
$date = new DateTime();
$date2 = new DateTime(date("yy-m-d h:i:s a", $t));
$diff = $date->getTimestamp() - $date2->getTimestamp() ;
echo $diff;
?></span>
<span id="<?echo $my_course['course_id']?>" class="timer" style="font-size:smaller;color:crimson;"></span>
<?php endif; ?>
<script>
var initialTime = <?echo $diff?>;
var seconds = initialTime;
function timer() {
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('<?echo $my_course['course_id']?>').innerHTML = days + "days " + hours + "hours " + minutes + "min " + remainingSeconds+ "sec left";
if (seconds == 0) {
learInterval(countdownTimer);
document.getElementById('<?echo $my_course['course_id']?>').innerHTML = "Completed";
} else {
seconds--;
}
}
var countdownTimer = setInterval('timer()', 1000);
</script>
What is the wrong I am doing and How to show the timer for every record
Your function name and call should also be unique.
EDIT
Also you messed up a log of code. I have commented the foreach loop and put my own for loop. Modify accordingly
Try this.
<?php
$my_course['course_id'] = 0;
for($i = 0; $i <= 2; $i++):
// foreach ($my_courses as $my_course):
// $course_details = $this->crud_model->get_course_by_id($my_course['course_id'])->row_array();
// You need to comment this out when you put your code live
$course_details['is_onlineclass'] = "Yes";
$course_details['live_class_schedule_time'] = time() + rand(0, 300);
$my_course['course_id'] += 1;
// remove till here
if ($course_details['is_onlineclass']==='Yes'):
?>
<span style="display:inline-block;font-size:12px;font-color:crimson;">
<?php
$t=$course_details['live_class_schedule_time'];
//time difference in seconds for coundown timer
$date = new DateTime();
$date2 = new DateTime(date("yy-m-d h:i:s a", $t));
$diff = $date->getTimestamp() - $date2->getTimestamp() ;
?>
</span>
<span id="<?php echo $my_course['course_id']; ?>" class="timer" style="font-size:smaller;color:crimson;"></span>
<?php endif; ?>
<script>
var initialTime = <?php echo $diff; ?>
var seconds = initialTime;
function timer<?php echo $my_course['course_id'];?>() {
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('<?php echo $my_course['course_id']?>').innerHTML = days + "days " + hours + "hours " + minutes + "min " + remainingSeconds+ "sec left";
if (seconds == 0) {
learInterval(countdownTimer);
document.getElementById('<?php echo $my_course['course_id']?>').innerHTML = "Completed";
} else {
seconds--;
}
}
var countdownTimer = setInterval('timer<?php echo $my_course["course_id"];?>()', 1000);
</script>
<?php endfor; ?>
EDIT: Here is your code
<?php
foreach ($my_courses as $my_course):
$course_details = $this->crud_model->get_course_by_id($my_course['course_id'])->row_array();
if ($course_details['is_onlineclass']==='Yes'):
?>
<span style="display:inline-block;font-size:12px;font-color:crimson;">
<?php
$t=$course_details['live_class_schedule_time'];
//time difference in seconds for coundown timer
$date = new DateTime();
$date2 = new DateTime(date("yy-m-d h:i:s a", $t));
$diff = $date->getTimestamp() - $date2->getTimestamp() ;
?>
</span>
<span id="<?php echo $my_course['course_id']; ?>" class="timer" style="font-size:smaller;color:crimson;"></span>
<?php endif; ?>
<script>
var initialTime = <?php echo $diff; ?>
var seconds = initialTime;
function timer<?php echo $my_course['course_id'];?>() {
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('<?php echo $my_course['course_id']?>').innerHTML = days + "days " + hours + "hours " + minutes + "min " + remainingSeconds+ "sec left";
if (seconds == 0) {
learInterval(countdownTimer);
document.getElementById('<?php echo $my_course['course_id']?>').innerHTML = "Completed";
} else {
seconds--;
}
}
var countdownTimer = setInterval('timer<?php echo $my_course["course_id"];?>()', 1000);
</script>
<?php endforeach; ?>

Take Query String and Display after button submission javascript

I'm making a calculator where a user can enter in a date, and it will display the time elapsed since. I've got it so that after the user clicks the submit button I've coded in, the page refreshes and displays a query string as follows:
file:///H:/dateselection/public_html/Document8.html?
Note the question mark at the end.
My question is, how do I take this and pass it into a value so that I can display it on my page? Here is my code:
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<Title>Elapsed Time Calculator</Title>
<body>
<!-- Navigation -->
<nav>
<ul class="w3-navbar w3-black">
<li>Home</li> <!--Link to Home Page-->
<li>NHL Teams</li><!--Link to Page of NHL Teams-->
<li>AHL Teams</li><!--Link to Page of AHL Teams-->
<li>WHL Teams</li><!--Link to Page of WHL Teams-->
<li>G.A.A. Calculator</li><!--Link to Page of WHL Teams-->
<li>Fan Survey</li><!--Link to Fan Survey Page-->
<li>Web Safety</li><!--Link to Page about Web Safety-->
<li>Elapsed Time</li><!--Link to Page That Calculates Elapsed Time Between Two Dates-->
</ul>
</nav>
<header>
<h1 style="text-align:center;">Elapsed Time Calculator</h1>
</header>
<article>
<form id="frmdate" onsubmit="myfunction()">
<fieldset>
<label for="dateSelected">
Select a date
</label>
<input type="date" id="dateSelected" />
</fieldset>
<fieldset class="button">
<button type="submit" id="determineDay">Calculate</button>
</fieldset>
</form>
</article>
<div id="output"></div>
<script src="tools.js"></script>
</body>
</html>
Here is my script file:
function myfunction()
{
var enteredDate = document.getElementById('dateSelected').valueAsDate;
var a= new Date();
var elapsed_time = a- enteredDate;
var result=elapsed_time.toString('days-hours-minutes-seconds');
//var result = "Day: " + elapsed_time.getDate() + "<br/>" +
// "Month: " + elapsed_time.getMonth() + "<br/>" +
// "Year: " + elapsed_time.getFullYear();
//document.getElementById('output').innerHTML = "Result is:<br/>" + result;
}
function secondsToString(result)
{
var numyears = Math.floor(result / 31536000);
var numdays = Math.floor(( result % 31536000) / 86400);
var numhours = Math.floor(((result % 31536000) % 86400) / 3600);
var numminutes = Math.floor((((result % 31536000) % 86400) % 3600) / 60);
var numseconds = (((result % 31536000) % 86400) % 3600) % 60;
return numyears + " years " + numdays + " days " + numhours + " hours " + numminutes + " minutes " + numseconds + " seconds";
}
In fact because you are using js and isn't really submitting anything, you can just disable form onsubmit and work with the "submit button" onclick event.
function myfunction() {
var enteredDate = document.getElementById('dateSelected').valueAsDate;
var a = new Date();
var elapsed_time = a - enteredDate;
var result = new Date(elapsed_time);
var result = "Day: " + result.getDate() + "<br/>" +
"Month: " + result.getMonth() + "<br/>" +
"Year: " + result.getFullYear();
document.getElementById('output').innerHTML = "Result is:<br/>" + result;
}
function secondsToString(result) {
var numyears = Math.floor(result / 31536000);
var numdays = Math.floor(( result % 31536000) / 86400);
var numhours = Math.floor(((result % 31536000) % 86400) / 3600);
var numminutes = Math.floor((((result % 31536000) % 86400) % 3600) / 60);
var numseconds = (((result % 31536000) % 86400) % 3600) % 60;
return numyears + " years " + numdays + " days " + numhours + " hours " + numminutes + " minutes " + numseconds + " seconds";
}
var calculateButton = document.getElementById('determineDay');
calculateButton.onclick = myfunction;
<form id="frmdate" onsubmit="return false;">
<fieldset>
<label for="dateSelected">
Select a date
</label>
<input type="date" id="dateSelected" />
</fieldset>
<fieldset class="button">
<button id="determineDay">Calculate</button>
</fieldset>
</form>
<div id="output"></div>

javascript timer for multiple auction item not working with php

I'm trying to implement a countdown timer for the online auction project, But it's only working for one item displayed. Here is the code:
<?php
$result=mysql_query("select * from `date`")or die(mysql_error());
while($row=mysql_fetch_array($result))
{
$then = $row['date'];
$now = time();
$thenTimestamp = strtotime($then) + strtotime($now);
$difference = $thenTimestamp - $now;
echo '<script type="text/javascript">
var seconds ='.$difference.';
function secondPassed() {
var hours=Math.round(seconds / 3600);
var minutes = Math.round(((seconds - 30)/60)%60);
var remainingSeconds = seconds % 60;
document.getElementById("countdown").innerHTML = hours+ ":"+ minutes + ":" + remainingSeconds;
if (seconds == 0) {
// clearInterval(countdownTimer);
document.getElementById("countdown").innerHTML = "Buzz Buzz";
} else {
seconds--;
}
}
setInterval("secondPassed()", 1000);
</script>
<body>
<span id="countdown"></span>
</body>';
}
?>
I have to submit my project on online auction by tomorrow. so, i need the solution. please help me out.
Thanks in advance.

24 hour Countdown timer using Javascript and PHP

I need a 24 hour countdown timer like the image in the link. I need to implement the timer to my wordpress site. The timer should reset every night at midnight EST.
This is my current JS Code but it restarts each time i refresh the page. Can I somehow integrate it with EST?
<script type = "text/javascript">
var timeInSecs;
var ticker;
function startTimer(secs) {
timeInSecs = parseInt(secs);
ticker = setInterval("tick()", 1000);
}
function tick( ) {
var secs = timeInSecs;
if (secs > 0) {
timeInSecs--;
}
else {
clearInterval(ticker);
startTimer(172800); // start again
}
var hours= Math.floor(secs/3600);
secs %= 3600;
var mins = Math.floor(secs/60);
secs %= 60;
var pretty = ( (hours < 10 ) ? "0" : "" ) + hours + ":" + ( (mins < 10) ? "0" : "" ) + mins + ":" + ( (secs < 10) ? "0" : "" ) + secs;
document.getElementById("countdown").innerHTML = pretty;
}
startTimer(86400); // 24 hours in seconds
</script>
<span id="countdown" style="font-weight: bold;"></span>
I'll take another look at this when I am home, your problem however is that every time your page loads you are calling the startTimer() method, what you need to do is get the current system time (in EST format) and convert that to seconds
That way when your page refreshes you will have the current time and not your current defined constant - I hope this is a basis for you to find a solution.
I got the answer. as Alex said, I need to get current system time(EST). I came up with index.html and server_time.php files.Here are codes for both files
INDEX.HTML
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Countdown</title>
<script src="http://code.jquery.com/jquery-2.1.0.js"></script>
<script>
var root_path = "http://localhost/countdown/";
function init(){
$.ajax({
type: "POST",
url: root_path + "server_time.php",
beforeSend: function(aj_msg) {
//$("#countdown").html('');
},
success: function(aj_msg){
$("#countdown").html('');
phpMsg = JSON.parse(aj_msg);
var est = "<span>" + Math.abs(phpMsg['ServerTime'][0].hour) + " :</span> ";
est += Math.abs(phpMsg['ServerTime'][0].minute) + " : " ;
est += Math.abs(phpMsg['ServerTime'][0].second);
$("#countdown").html(est);
}
})
}
setInterval(init, 1000)
</script>
</head>
<body>
<div id="countdown"></div>
</body>
</html>
And server_time.php
<?php
date_default_timezone_set('US/Eastern');
$currenttime = date('G:i:s:u');
list($hrs,$mins,$secs,$msecs) = split(':',$currenttime);
$output = '{"ServerTime": [';
$hrs -= 24;
$mins -= 60;
$secs -= 60;
$output .= '{ "hour":"' . $hrs . '" , "minute":"' . $mins . '", "second":"' . $secs . '"}';
$output .=']}';
echo $output;
?>

Categories

Resources