how to use javascript timer in a nested repeater? - javascript

I'm trying to add a javascript timer for products, if the item have a promotion then show the timer and start the count down.. so what i'm doing is im sending the end date from code behind to the javascript function and the function creates the timer based on the end date. I've been trying for long time the script is working, the issue is i'm not able to loop inside the nested repeater to get the correct countdown control id and index.
hope you guys can help me with this issue.
thanks
HTML Code:
<asp:Repeater runat="server" ID="Repeater1" OnItemDataBound="rptdep_ItemDataBound" OnItemCommand="rptdep_Details_Command">
<ItemTemplate>
<asp:LinkButton class="navbar-brand" runat="server" ID="LinkButton1" Style="text-decoration: none; margin-right: -25px; border: none; font-size: medium" CommandArgument='<%#Eval("department_code") %>' CommandName="more">
<asp:Repeater runat="server" ID="rptdeppromo" OnItemDataBound="rptdeppromo_ItemDataBound" OnItemCommand="Item_depPromo_Command">
<ItemTemplate>
<div runat="server" id="countdown" class="cntdwn"></div>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
Timer JS code:
function producttimer(compntname, enddate1, col) {
$(document).ready(function () {
var $countdown = $('#rptdep_rptdeppromo_' + compntname + '_countdown_' + col);
// set the date we're counting down to
var target_date = new Date(enddate1);
// variables for time units
var days, hours, minutes, seconds;
// update the tag with id "countdown" every 1 second
setInterval(function () {
target_date.getTime();
// find the amount of "seconds" between now and target
var current_date = new Date().getTime();
// check for match
if (current_date === target_date) {
}
var seconds_left = (target_date - current_date) / 1000;
// do some time calculations
days = parseInt(seconds_left / 86400);
seconds_left = seconds_left % 86400;
hours = parseInt(seconds_left / 3600);
seconds_left = seconds_left % 3600;
minutes = parseInt(seconds_left / 60);
seconds = parseInt(seconds_left % 60);
// format countdown string + set tag value
$countdown.text(days + "days, " + hours + "hrs, " + minutes + "min, " + seconds + "s");
}, 1000);
}); //EOF DOCUMENT.READY
}
C# parent repeater code:
protected void rptdep_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Repeater innerRepeater2 = (Repeater)e.Item.FindControl("rptdeppromo");
DataRowView drv = (DataRowView)(e.Item.DataItem);
}
}
}
C# nested repeater code:
protected void rptdeppromo_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
DataRowView drv = (DataRowView)(e.Item.DataItem);
DateTime EndDate = Convert.ToDateTime(Convert.ToDateTime(drv.Row["publishtdt"]).ToString("dd MMM yyyy"));
int countw = 0;
int count = 0;
if (total < 30)
{
count += 1;
foreach (RepeaterItem item in rptdep.Items)
{
countw += 1;
}
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "counter" + countw, "producttimer('" + countw + "','" + EndDate + "', '" + e.Item.ItemIndex + "');", true);
}
else
{
}
}
}

here is a different approach:
1- in your repeater, display all Promotions End date in label, and give them the same class "cntdwn"
2- your JS , when the page is ready it will look all items in your page with the same class and loop inside them:
var elements = document.getElementsByClassName("cntdwn");
for (var i = 0, len = elements.length; i < len; i++)
{
var PromoID = elements[i].Id;
Var EndDate = document.getElementById(PromoID).textContent;
}
3- Now you have the Lable ID , and The end Date , use your countdown logic to display the countdown in the text area of that ID.
Good luck ...

the upvoted answer worked for me, but i needed to tweak it a bit. I thought some code may help the next person who looks here.
using the plugin jquery.countup.js (any counter should work):
<div id="div<%# ((RepeaterItem)Container).ItemIndex + 1%>" class="countdown">
<%# Eval("EntryDate") %>
</div>
<script type="text/javascript">
$(function () {
var elements = document.getElementsByClassName('countdown');
var len = elements.length;
for (var i = 0; i < len; ++i) {
var timerID = elements[i].id;
var startDate = elements[i].innerText;
startCounter(startDate, timerID);
};
});
function startCounter(entryDate, timerID) {
var entDate = new Date(entryDate);
var year = (entDate).getFullYear();
var month = (entDate).getMonth() + 1;
var day = (entDate).getDate();
var hour = (entDate).getHours();
var min = (entDate).getMinutes();
var sec = (entDate).getSeconds();
$("#" + timerID).empty();
$("#" + timerID).countup({
start: new Date(year, month, day, hour, min, sec) //year, month, day, hour, min, sec
});
};

Related

How to calculate time difference using jQuery

I have code for calculating time difference and it works well. I need to change the method (actually I added one more method in certain condition). The method that I added in a condition when the textbox has value Istirahat, and then I need to change the method to the time difference that I made minus one hour.
I think it will be confusing to see my explanation without the code.
Here's the code:
$(document).ready(function() {
var $time1 = $("#start");
var $time2 = $("#end");
var $diff = $("#jam_total");
function updateHours() {
var dtStart = new Date("7/20/2015 " + $time1.val());
var dtEnd = new Date("7/20/2015 " + $time2.val());
var stats1 = $("#status_check").val();
if(stats1!='ISTIRAHAT') {
var diff = ((dtEnd - dtStart)) / 1000;
} else if(stats1!='TANPA ISTIRAHAT') {
var diff = ((((dtEnd - dtStart)) / 1000) - 1);
}
var totalTime = 0;
if (diff > 60*60*12) {
totalTime = formatDate(60*60*12);
} else {
totalTime = formatDate(diff);
}
$diff.val(totalTime);
}
function formatDate(diff) {
var hours = parseInt(diff / 3600) % 24;
var minutes = parseInt(diff / 60) % 60;
var seconds = diff % 60;
return (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes);
}
$("#option2").on("change", function() {
if($time1.val() && $time2.val()) {
updateHours();
}
});
});
<input type="time" id="start" name="logintime"/>
<input type="time" id="end"name="logouttime" />
<br /><br />
<select name="option2" id="option2" onchange="Choose1(this)" style="float:left">
<option value="-">-</option>
<option value="istirahat">istirahat</option>
<option value="tanpa istirahat">tanpa istirahat</option>
</select>
<input type="text" name="status_check" size="8" readonly="readonly" id="status_check" style="text-transform:uppercase" />
<br /><br />
Total: <input type="text" id="jam_total" type="text" name="jam_total" size="18" readonly="readonly">
<br /><br />
<script>
function Choose1(data) {
document.getElementById("status_check").value = data.value;
}
</script>
Try to check the jQuery function at the code like this:
else if (stats1 != 'TANPA ISTIRAHAT') {
var diff = ((((dtEnd - dtStart)) / 1000) - 1);
}
var diff = (((dtEnd - dtStart)) / 1000) - 1) is what I mean, that code won't work perfectly like I want. What I want is like this:
Please check the code inside if var diff = ((dtEnd - dtStart)) / 1000; I want the result of this code to be minus one hour.
First of all there is one thing wrong, you need to set stats1 to UpperCase, otherwise you can't compare correct. Second thing is you are calculating time over seconds, you should minus 60*60 (3600 to minus 1 hours).
function updateHours(){
var dtStart = new Date("7/20/2015 " + $time1.val());
var dtEnd = new Date("7/20/2015 " + $time2.val());
var stats1 = $("#status_check").val().toUpperCase();
// if you don't add toUpperCase, istirahat won't be equal to ISTIRAHAT so everytime..
// first if block will be executed
if(stats1!='ISTIRAHAT'){
var diff = ((dtEnd - dtStart)) / 1000;
}
else if(stats1!='TANPA ISTIRAHAT'){
var diff = ((((dtEnd - dtStart)) / 1000) - 3600); // and you should minus 3600
}
var totalTime = 0;
if (diff > 60*60*12) {
totalTime = formatDate(60*60*12);
;
} else {
totalTime = formatDate(diff);
}
$diff.val(totalTime);
}
Here is the working fiddle
Hope helps,

multiple alarm clock in javascript using dynamic generated input elements in javascript

I am trying to make a web page which will allow to set multiple alarms using dynamic element creation property of javascript but I'm not able to get the values of these multiple elements and create a alert on that time.
This is my code so far
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br />
<input id="btnAdd" type="button" value="add" onclick="AddTextBox();" />
<script type="text/javascript">
var room = 0;
var i = 0;
function GetDynamicTextBox(){
return '<div>Alarm ' + room +':</div><input type="number"style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" placeholder="hour" id="a'+room+'" /><input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" /><input type="date" style="margin:auto;text-align:center; width:200px; padding:10px"><input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var html = "";
html += "<div>" + GetDynamicTextBox() + "</div>";
document.getElementById("TextBoxContainer").innerHTML = html;
room++;
}
window.onload = RecreateDynamicTextboxes;
function AddAlarm(values){
var hour = document.getElementById('');
var minute = document.getElementById('');
var date = document.getElementById('');
}
</script>
To create a notification whenever a given time or state is reached, I think you are looking for setInterval (see reference).
This method allows you to take action at a regular interval and it tries to honor that interval the best it can. It opens to a common mistake if your action can take longer than that interval duration so be careful not using a too short interval. In such case, actions can overlap and weird behavior will occur. You do not want that to happen so don't be too greedy when using that.
For an alarm project, I would recommend an interval of one second.
Example (not tested):
JavaScript
var alarmDate = new Date();
alarmDate.setHours(7);
alarmDate.setMinutes(15);
// set day, month, year, etc.
var ONE_SECOND = 1000; // miliseconds
var alarmClock = setInterval(function() {
var currentDate = new Date();
if (currentDate.getHours() == alarmDate.getHours() &&
currentDate.getMinutes() == alarmDate.getMinutes()
/* compare other fields at your convenience */ ) {
alert('Alarm triggered at ' + currentDate);
// better use something better than alert for that?
}, ONE_SECOND);
To add dynamic alarms, you could put them into an array then have your setInterval iterate over it.
In the long run you will probably get sick of alert and feel the need to use something that doesn't break the flow of your application. There are a lot of possibilities, one being the use of lightboxes that could stack over each other. That way you would be able to miss an alarm and still be notified by the next one.
Hope this helps and good luck!
You forgot the ID attribute on the date input and you were collecting the input elements in AddAlarm instead of their values.
EDIT: To check the alarms you have to store them and check every minute, if the current date matches one of the alarms. I added a short implementation there.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br />
<input id="btnAdd" type="button" value="add" onclick="AddTextBox();" />
<script type="text/javascript">
var alarms = {};
var room = 0;
var i = 0;
setInterval(function() {
var current = new Date();
for (var nr in alarms) {
var alarm = alarms[nr];
console.log("checking alarm " + nr + " (" + alarm + ")");
if(current.getHours() == alarm.getHours()
&& current.getMinutes() == alarm.getMinutes()) { // also check for day, month and year
alert("ALERT\n"+alarm);
} else{
console.log('Alarm ' + nr + '('+alarm+') not matching current date ' + current);
}
}
}, 60000);
function GetDynamicTextBox(){
return '<div>Alarm ' + room +':</div><input type="number"style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" placeholder="hour" id="a'+room+'" /><input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" /><input type="date" style="margin:auto;text-align:center; width:200px; padding:10px" id="c'+room+'"><input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var html = "";
html += "<div>" + GetDynamicTextBox() + "</div>";
document.getElementById("TextBoxContainer").innerHTML = html;
room++;
}
window.onload = RecreateDynamicTextboxes;
function AddAlarm(values){
var hour = $('#a'+values).val();
var minute = $('#b'+values).val();
var date = $('#c'+values).val();
console.log(hour + ':' + minute + ' on ' + date);
var dateObj = new Date(date);
dateObj.setMinutes(minute);
dateObj.setHours(hour);
console.log(dateObj);
alarms[values] = dateObj;
}
</script>
So far I'm able to generate a alert when the values match the system time but I don't know how to delete the array value when an element is deleted. I am not able to do it. This is my code so far:
<script type="text/javascript">
var snd = new Audio("clock.mp3"); // buffers automatically when created
// Get
if (localStorage.getItem("test")) {
data = JSON.parse(localStorage.getItem("test"));
} else {
// No data, start with an empty array
data = [];
}
var today = new Date();
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
//since page reloads then we will just check it first for the data
function check() {
//current system values
console.log("inside check");
//if time found in the array the create a alert and delete that array object
for(var i = 0; i < data.length; i++) {
var today = new Date();
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
if (data[i].hours == h && data[i].minutes == m && data[i].dates == d ) {
data.splice(i,1);
localStorage["test"] = JSON.stringify(data);
snd.play();
alert("Wake Up Man ! Alarm is over ");
}
}
if((data.length)>0)
{
setTimeout(check, 1000);
}
}
//we do not want to run the loop everytime so we will use day to check
for(var i =0 ; i< data.length; i++)
{
if((data[i].dates == d) && (data[i].hours >= h) && (data[i].minutes >= m) )
{
check();
}
}
console.log(data);
var room = 1;
//var data = [];
var i = 0;
function GetDynamicTextBox(){
var date = new Date();
var h = date.getHours();
var m = date.getMinutes();
var d = date.getDay();
return '<div>Alarm ' + room +':</div><input type="number" style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" value ='+h+' placeholder="hour" id="a'+room+'" /> <input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" value ='+m+' /> <select id="c'+room+'" style="margin:auto; width:150px; padding:10px; color: black" required> <option value="1">Monday</option> <option value="2">Tuesday</option> <option value="3">Wednesday</option> <option value="4">Thursday</option> <option value="5">Friday</option> <option value="6">Saturday</option> <option value="0">Sunday</option> </select> <input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
}
function AddTextBox() {
room++;
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var html = "";
html += "<div>" + GetDynamicTextBox() + "</div>";
document.getElementById("TextBoxContainer").innerHTML = html;
}
window.onload = RecreateDynamicTextboxes;
function AddAlarm(values){
var hour = $('#a'+values).val();
var minute = $('#b'+values).val();
var date = $('#c'+values).val();
//get the current time and date
var today = new Date();
//current system values
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
//first check that whether a same date present in the array or not then push it
var found = -1;
for(var i = 0; i < data.length; i++) {
if (data[i].hours == hour && data[i].minutes == minute && data[i].dates == date ) {
found = 0;
break;
}
}
//if value does not present then push it into the array
if(found == -1)
{
data.push({hours: hour, minutes: minute, dates: date});
//storing it into localstorage
localStorage.setItem("test", JSON.stringify(data));
}
else
{
alert("Same value Exists");
}
//console.log(data);
function check() {
//current system values
//console.log("inside check");
//if time found in the array the create a alert and delete that array object
for(var i = 0; i < data.length; i++) {
var today = new Date();
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
if (data[i].hours == h && data[i].minutes == m && data[i].dates == d ) {
data.splice(i,1);
snd.play();
alert("Wake Up Man ! Alarm is over ");
}
}
if((data.length)>0)
{
setTimeout(check, 1000);
}
}
//we do not want to run the loop everytime so we will use day to check
for(var i =0 ; i< data.length; i++)
{
if((data[i].dates == d) && (data[i].hours >= h) && (data[i].minutes >= m))
{
check();
}
}
}
</script>

Why does the text keep repeating without a for loop?

I am making a code that will give two different types of clocks depending on the radio button selected. When the clock appears, the text saying "Reload the page to go back to clock settings. However, when the 12 hour clock radio button is selected, the text is repeated every second. Is there any way to fix this? And please do not use J Query, I do not know it.
function clock_12() {
document.write("<div align='center' style = 'background:#420080; color:limegreen'>"+"Reload the page to go back to the clock settings."+"</div>");
var clocktime = new Date();
var hours = clocktime.getHours();
var mins = clocktime.getMinutes();
var secs = clocktime.getSeconds();
var ampm = (hours >= 12) ? "P.M." : "A.M.";
if (hours >= 13) {
hours -= 12;
}
if (hours < 1) {
hours = 12;
}
if (mins < 10) {
mins = "0" +mins;
}
if (secs < 10) {
secs = "0" +secs;
}
document.write("<div id = 'the_clock' align = 'center' style = 'background:#420080; color:limegreen'></div>");
var div_clock = document.getElementById("the_clock");
div_clock.innerHTML = hours + ":" +mins+ ":" +secs+ " " +ampm;
setTimeout("clock_12()", 1000);
}
function clock_24() {
var clocktime = new Date();
var hours = clocktime.getHours();
var mins = clocktime.getMinutes();
var secs = clocktime.getSeconds();
var back = "Reload the page to go back to the clock settings.";
document.writeln("<div align='center' style = 'background:#420080; color:limegreen'>"+back+"</div>");
if (mins < 10) {
mins = "0" +mins;
}
if (secs < 10) {
secs = "0" +secs;
}
document.write("<div id = 'clock' align = 'center' style = 'background:#420080; color:limegreen'</div>");
var div_clock = document.getElementById("clock");
div_clock.innerHTML = hours + ":" +mins+ ":" +secs;
setTimeout("clock_24()", 1000);
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>12 and 24 Hour Clocks</title>
</head>
<body style="background:limegreen">
<table style="width:50%" align = "center">
<tr>
<td><script type = "text/javascript" src = "clock.js"></script></td>
</tr>
<tr>
<br /><br /><td style = "background:#420080; color:limegreen"><label for="clock12">12 Hour Clock</label><input type = "radio" onclick = "clock_12()" id = "clock12" value = "clock12"></td>
<br /><br /><td style = "background:#420080; color:limegreen"><label for="clock24">24 Hour Clock</label><input type = "radio" onclick = "clock_24()" id = "clock24" value = "clock24"></td>
</tr>
</table>
</body>
</html>
You have the line
document.write("<div id = 'clock' align = 'center' style = 'background:#420080; color:limegreen'</div>");
Inside your clock_24 function, which gets called every second because of this: setTimeout("clock_24()", 1000);. The same for clock_12. So, remove those lines from your functions. Put it outside, like at the beginning of the file clock.js. Check http://www.w3schools.com/jsref/met_win_settimeout.asp
EDIT: sorry, it is more than one line. You have do put all of your document.write outside of your functions.
EDIT: roshen_amin correctly commented that the html needs to be written on click. So the complete solution is to make a function that does the document.write, and then calls clock_24()/clock_12(). On click, call that function instead of clock_24()/clock_12(). Like that, the html appears when you click, but only the rest of the function is called every second

Working Out JavaScript Time with PHP Time

I am working on a page that pulls data from DB. PHP time() is captured and saved to the DB alongside user contents.
I want to be about to subtract the capturedTime from the current time using JavaScript and display how long the post has been made in hr : min : s and should be live.
HTML:
<div class = 'responses'>
<p class = 'capturedTime' style='display: none;'>123456789</p>
</div>
jQuery:
$(document).on('click', '.responses', function () {
$this = $( this );
timeC = $this.prev('.capturedTime').text();
timeNow = $.now()
timeLapsed = ( timeNow - timeC )/1000;
seconds = timeLapsed/60;
mins = seconds/60;
hrs = mins/24;
if ( timeLapsed !== NaN ){
alert(seconds + '------' + mins + '---' + hrs);
}
});
I suggest you to change your code this way:
Fiddle
<body>
<div class='responses'>
<p class='capturedTime' data="1401270715145"></p>
</div>
</body>
var $times, timer;
$times = $('.capturedTime');
timer = setInterval(function () {
var i, len, cache, value, now, minutes, seconds;
for (i = 0, len = $times.length; i < len; i = i + 1) {
cache = $times.eq(i);
now = new Date().getTime();
value = new Date(now - parseInt(cache.attr("data")));
minutes = value.getMinutes();
seconds = value.getSeconds();
cache.html("m:" + minutes + " ss:" + seconds);
}
}, 1000);
try this :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://timeago.yarp.com/jquery.timeago.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
var lastUpdate = new Date($(".capturedTime").html()*1000)
alert($.timeago(lastUpdate));
});
</script>
or visit this page

Run function for 30 min

Here's what I want to do.
Execute a function : once, at some time of the day.
The function run for 30 minutes.
I've tried setTimeout but it doesn't fit my requirement because it run the function after X millisecond. Whereas I need the function to execute right away, at desired time for 30 minutes. Code as attached.
var d = new Date();
var hour = d.getHours();
var minute = d.getMinutes();
var day = self.getDate();
var month_name=new Array(12);
month_name[0]="January"
month_name[1]="February"
month_name[2]="March"
month_name[3]="April"
month_name[4]="May"
month_name[5]="June"
month_name[6]="July"
month_name[7]="August"
month_name[8]="September"
month_name[9]="October"
month_name[10]="November"
month_name[11]="December"
var month = month_name[self.getMonth()];
var fullDate = month+' '+day+' '+hour+':'+minute;
function someFunction() {}
function closeFunction(){
noticeDiv.css('display', 'block');
mainDiv.css('display', 'none');
}
function executeFunction(targetDate){
if (fullDate == targetDate){
setTimeout ( closeFunction(), 180000 );
}else{
someFunction();
}
}
executeFunction(targetDate);
Use setInterval Function
Syntax-> var interval = setInterval(function(){function_name()},timeout In milliseconds);
To clear Interval or stop function we use ->clearInterval(interval);
HTML
<!-- Hide by default, show at target time -->
<div id="noticeDiv" style="display: none">
<h2>Registration Closed.</h2>
</div>
<!-- Show by default, hide at target time -->
<div id="mainDiv">
<h2>Registration Open.</h2>
</div>
jQuery
$(document).ready(function () {
var d = new Date();
var hour = d.getHours();
var minute = d.getMinutes();
var day = d.getDate();
var month_name = new Array(12);
month_name[0] = "January"
month_name[1] = "February"
month_name[2] = "March"
month_name[3] = "April"
month_name[4] = "May"
month_name[5] = "June"
month_name[6] = "July"
month_name[7] = "August"
month_name[8] = "September"
month_name[9] = "October"
month_name[10] = "November"
month_name[11] = "December"
var month = month_name[d.getMonth()];
var fullDate = month + ' ' + day + ' ' + hour + ':' + minute;
console.log(fullDate);
fulldate = 'May 3 17:1';
function executeFunction(targetDate) {
x = 0;
if (fulldate == targetDate) {
//set closing time of function 180000 = 30 min.It will hide div registration open and show registration closed div.
interval = setInterval(closeFunction, 180000);
} else {
openFunction();
}
}
function openFunction() {
console.log('Registration is now open')
}
function closeFunction() {
x++;
$('#mainDiv').append(x);
if (x == 1) {
$('#noticeDiv').show();
$('#mainDiv').hide();
clearInterval(interval);
}
}
// Execute time
executeFunction('May 3 17:1');
});
Working Demo http://jsfiddle.net/cse_tushar/8r5T8/

Categories

Resources