I have been using this script ( http://www.dynamicdrive.com/dynamicindex6/dhtmlcount.htm ) for countdown to vacations. But this time i need to have 2 countdowns on ONE page. I tried having 2 different pages with one script in each and include them to the main page, but that did not work.
Anyone know how to edit it or have a script that works for this purpose? I tried editing some of the variables but I were unable to get it to work.
Thanks.
I have cooked up a simple countdown Constructor which may help you further.
function countDown(startTime, divid, the_event){
var tdiv = document.getElementById(divid)
,start = parseInt(startTime.getTime(),10)
,the_event = the_event || startTime.toLocaleString()
,to;
this.rewriteCounter = function(){
var now = new Date().getTime()
,diff = Math.round((start - now)/1000);
if (startTime > now)
{
tdiv.innerHTML = diff +' seconds untill ' + the_event;
}
else {clearInterval(to);}
};
this.rewriteCounter();
to = setInterval(this.rewriteCounter,1000);
}
//usage
var count1 = new countDown(new Date('2010/12/11 10:44:59')
,'counter1'
,'tomorrow 10:45');
var count2 = new countDown(new Date('2010/12/25')
,'counter2'
,'first christmas day');
Check it out #jsfiddle
Related
I have searched online to get my result but i wasn't able to come across any right solution.
I want my page to automatically show a popup everyday by 5:00PM without refreshing the page.
So, if i visit a page by 4:50Pm or anytime before 5:00PM, Once i am still on that page, it should auto pop up a div without refreshing the page.
I tried using this code but i have to refresh the page before it works which doesn't seem efficient.
$(document).ready(function() {
var currentTime = toUTC(new Date());
var startTime = toUTC(new Date());
var endTime = toUTC(new Date());
startTime.setHours(20);
startTime.setMinutes(10);
startTime.setSeconds(59);
endTime.setHours(20);
endTime.setMinutes(0);
endTime.setSeconds(0);
var currentTimez = (currentTime.getHours() + 1);
if (currentTimez == 20 && currentTime.getMinutes() == 20){
popup();
}
});
function popup() {
alert("Thanks")
}
function toUTC(inDate) {
inDate.setMinutes(inDate.getMinutes() + inDate.getTimezoneOffset());
return inDate;
}
I don't mind if i have to hit the db to get this done or using cookies.
you need to use a timer
var current = new Date();
var fivePM = new Date(current.getYear(), current.getMonth(), current.getDayOfMonth());
fivePM.setHour(17);
if (current < fivePM) {
var diff = fivePM.getTime() - current.getTime();
}
var timerID = setTimeout(popup, diff);
I have a popup which is loaded after 30 seconds of viewing the homepage. Is it possible to have it load after 30 seconds of browsing the site and not just a particular page?
Thanks.
Update:
Current code still only loads the box after 30 seconds on each page load
var myDaemon = '';
localStorage.setItem('myTimestamp', Date.now());
if(myDaemon) clearInterval(myDaemon);
myDaemon = setInterval(function(){
var TimeDiffinSeconds = (Date.now() - localStorage.myTimestamp) / 1000;
if( TimeDiffinSeconds > 30){
requestcallback();
clearInterval(myDaemon);
localStorage.myTimestamp = Date.now();
}
},1000);
function requestcallback(){
// localStorage.clear();
var popup
if(localStorage["popup"] != null){
var timestamp = new Date().getTime(),
last_here = new Date();
last_here.setTime(localStorage["popup"]);
var current = last_here.getTime() + (7 * 24 * 60 * 60 * 1000);
if(current < timestamp){
popup = setTimeout(showPopup, 1);
}
}
else{
popup = setTimeout(showPopup, 1);
}
function showPopup(){
jQuery('.overlay').fadeIn();
clearTimeout(popup);
}
jQuery('.overlay .close').click(function(){
jQuery('.overlay').fadeOut();
var current = new Date().getTime();
localStorage["popup"] = current;
});
}
You could use Local Storage in order to save a time-stamp the moment the user visits the site , and then code a simple SetInterval to check that timestamp in specific intervals. If the difference between the current timestamp and the one saved is more than 30 seconds , you can launch your popup.
This is tricky with Javascript though. Depending on your Sites Design a different Approach is required. Also if it is for Security reasons , this is best done with AJAX and Validation through a Server. Javascript can be easily manipulated / prevented from a user and your code can be easily avoided.
A simple Example to get you going :
At your index page insert the following code :
<script>
var myDaemon = '';
localStorage.setItem('myTimestamp', Date.now());
</script>
We have declared a "var myDaemon = '';" so that we can hold our Daemons IDs in there and effectively Clearing them from any of our pages later.
Then at the Pages that you want to check for activity insert the following code :
if(myDaemon) clearInterval(myDaemon);
myDaemon = setInterval(function(){
var TimeDiffinSeconds = (Date.now() - localStorage.myTimestamp) / 1000;
if( TimeDiffinSeconds > 30){
alert('You have been browsing for more than 30 Seconds');
clearInterval(myDaemon);
localStorage.myTimestamp = Date.now();
}
},1000);
The if(myDaemon) clearInterval(myDaemon); is there to make sure we do not overlap Daemons and end up with a million of Alerts after visiting a few pages.
The clearInterval(myDaemon); after the alert is there to make sure that we stop the Daemon when we reach our goal.
The localStorage.myTimestamp = Date.now(); is there to make sure we reset our localstorage to a new Timestamp , in order to recalculate the activity of the user (if needed).
1) Define cookie functions (copy from w3school)
function setCookie(cname, cvalue, exdays) {...}
function getCookie(cname) {...}
function checkCookie() {...}
2) Create cookie if user doesn't have one
getCookie('user_first_visited') || setCookie('user_first_visited', Date.now());
3) Loop detecting if user visited over 30 seconds
if (!getCookie('user_popup_triggerred')) {
var loopDetect = setInterval(function(){
var TimePast = (Date.now() - getCookie('user_first_visited')) / 1000;
if( TimePast > 5){
alert('Browsed any page more than 5 Seconds');
clearInterval(loopDetect);
setCookie('user_popup_triggerred', 1);
}
}, 1000);
}
See jsfiddle, you can try it on two pages and you should not get popupBox on page reload after triggered once. Clean your browser cookie to try again.
From some days I am working in html full calender, my default view is week view, I want to copy one week events into next week by click in html button. I got event array by below mention code but I am not getting, how should I copy this events into next week, I have googled but didn't get any thing regarding this. Please help to resolve this Thanks in advance.
$('#btn_copy_calendar_next_week').click(function () {
$('#calendar').fullCalendar('next');
events = $('#calendar').fullCalendar('clientEvents');
console.log(events);
});
I got solution of my own problem after very long time, it works for me I hope this will help other too, whoever need it.
$('#btn_copy_calendar_next_week').click(function () {
all_events = $('#calendar').fullCalendar('clientEvents');
var current_view = $('#calendar').fullCalendar('getView');
var start_date=current_view.start;
var end_date=current_view.end;
var event_obj = new Object();
var check_current_week_event=false;
all_events.forEach(function(evnt) {
if (evnt['start'].format() >= start_date.format() && evnt['end'].format() <= end_date.format()){
--l;
check_current_week_event=true;
D1=evnt['start']._d;
console.log(D1);
D2=evnt['end']._d;
var X1=D1.format("yyyy-mm-dd'T'HH:MM:ss'Z'");
var X2=D2.format("yyyy-mm-dd'T'HH:MM:ss'Z'");
var XD1=new Date(X1);
var XD2=new Date(X2);
XD1.setUTCDate(XD1.getUTCDate() + 7);
XD2.setUTCDate(XD2.getUTCDate() + 7);
var str_d1 = convertLocalDateToUTCDate(XD1,true);
var str_d2 =convertLocalDateToUTCDate(XD2,true);
var mb_test1 = convertLocalDateToUTCDate(str_d1,true);
var mb_test2 = convertLocalDateToUTCDate(str_d2,true);
event_obj.id='vkm_test'+l;
event_obj.title=evnt['title'];
event_obj.start= mb_test1.format("yyyy-mm-dd'T'HH:MM:ss'Z'");
event_obj.end= mb_test2.format("yyyy-mm-dd'T'HH:MM:ss'Z'");
event_obj.allDay = false;
event_obj.offer_id=evnt['offer_id'];
console.log('=========================');
customData = {
'event_id':"chunked-test"+l,
'offer_id':event_obj.offer_id,
'title': event_obj.title,
'start':event_obj.start,
'end':event_obj.end,
'rest_id':{{restaurant.restaurant_id}}
};
console.log(event_obj.start);
console.log(event_obj.end);
// $('#calendar').fullCalendar( 'renderEvent',event_obj);
$("#calendar").fullCalendar( "removeEvents", "chunked-helper");
$("#calendar").fullCalendar( "addEventSource",chunk_test(event_obj,'test'+l));
offers_list.push(customData);
}
});
if(check_current_week_event==true){
$('#calendar').fullCalendar('next');}
else{
$('#hd_id').text('DealMonk');
$('#txt_error_msg').text('There is Nothing to Copy in Next Week!');
$('#error_msg').modal('show');
}
});
Happy Coding..
Sorry, i am not sure if I am asking the question correctly. When a date is changed by a user the date count down changes on the page. If the date is changed more than once it flashes all date changes. I guess it is storing the previous information somewhere. I have tried clearing the vars.
var deal_yeax = '';
as I would do in php with no luck
$('#deal_end').focusout(function() {
var deal_end = $("#deal_end").val();
var array = deal_end .split('-');
var deal_montx = array[0];
var deal_dax = array[1];
var deal_yeax = array[2];
deal_montx = deal_montx - 1;
$(function(){
ts = new Date(deal_yeax , deal_montx , deal_dax );
$(".h").countdown({
timestamp : ts,
callback : function(days, hours, minutes, seconds){
message_days = (days);
var message_hours = (hours);
$(".message_hours").text(message_hours + " Hours");
var message_minutes = (minutes);
$(".message_minutes").text(message_minutes + " Minutes");
var message_seconds = (seconds);
// Creat the display
if ( message_days < 1 && message_hours < 1 ) { $(".message_seconds").text(message_seconds + " Seconds"); }
else if ( message_days < 1 && message_hours > 1 ) { }
else if ( message_days == 1 ) { $(".message_days").text(message_days + " Day"); }
else { $(".message_days").text(message_days + " Days"); }
if ( message_days < 1 && message_hours < 1 && message_minutes < 1 && seconds < 1 ) {
$(".hide_my_buy_button").fadeOut("fast");
}
}
});
});
});
Everytime you "focusout" from #deal_end, you'll attach a countdown event to .h. Without knowing exactly how countdown(...) works (It'll be good if you provide the source so we can provide more help!), one way to fix the issue maybe to use JQuery's unbind(...) function to remove existing listeners on an event before adding a new one to it.
Here's an example on the issue:
<!-- HTML -->
<div>
<input id="text" />
<button id="clicker" />
</div>
<!-- Javascript -->
$('#text').focusout(function() {
var text = this.value;
// Everytime #text is "focused out", a new event is registered with #clicker.
$('#clicker').click(function() {
console.log('Value: ' + text);
});
});
... and here's how to solve the issue (It's just one of the many ways. This way is probably not the most elegant but anyhow.)
$('#text').focusout(function() {
var text = this.value;
$('#clicker').unbind('click');
// Everytime #text is "focused out", a new event is registered with #clicker.
$('#clicker').click(function() {
console.log('Value: ' + text);
});
});
Bottom line: It seems focusout(...) is adding a new countdown everytime it is triggered. That might be the problem you're having.
Not sure if this helps? Lemme know.
P.S. JSFiddle to go with it: http://jsfiddle.net/PE9eW/
The problem seems to be with .countdown function that you are using in your code to flash the date changes. When you assign a new count down object to $(".h") the plugin or the function probably assign some event handler or interval to it, but it doesn't seem to clear the old ones when it is called again and that is why it flashing all the dates for each countdown. So you will have to do it manually. I am not sure if you are using an external plugin or is it your own function but what you need to do is to clear the existing events or intervals that is assigned to your element when you call the function. I can be more helpful if you tell me which plugin you are using or maybe show the code if it is your own function. (referring to .countdown() )
i am writing a animation with javascript and want to print to user loading time until all images loaded.
images set in html as: <img src="" />
are there javascript code to know when all page loaded?
i.e time until onLoad() event called
You might be able to do something like this at the bottom of the page
<span id="imgsMsg"></span>
<script type="text/javascript">
var imgs = document.images;
var len = imgs.length;
var percent = 100;
var count=0;
var messagecontainer = document.getElementById("imgsMsg");
for (var i=0;i<len;i++) {
imgs[i].onload=function() {
count++;
messagecontainer = (percent - Math.floor((100/len)*count))+"% loaded"; // hope my math is correct ;)
}
}
</script>
</body>
The best you can probably do is to track the number of images that have been loaded, and divide that into the total number of images remaining. Something like this:
var total_loaded = 0;
$('img').load(function()
{
total_loaded += 1;
var load_progress = total_loaded / $('img').length;
// you can now use load_progress to show the user a rough progress animation
} );
If you want a "time remaining" display, you'll need to fake it. You could track the total time elapsed and compare that to the load_progress variable to get the remaining time, for example.
This isn't hard to do, with $(window).load:
var readytime = new Date().getTime();
$(window).load(function() {
var loadingtime = (new Date().getTime() - readytime) / 1000; // in seconds
$('#yourTimingField').text(loadingtime + ' seconds');
});
This measures the amount of time between the this part of the script and the loading of all subelements.