I need to create a popup window that open on page load AND only between 11am and 7pm EST.
I have the auto pop up working, but am having trouble adding the time variance.
Please advise.
EDITED
<!--chat-->
<script type="text/javascript">
$(document).ready(function() {
var currentTime = new Date((new Date()).toUTCString());
var startTime = new Date((new Date()).toUTCString());
var endTime = new Date((new Date()).toUTCString());
startTime.setUTCHours(8);
endTime.setUTCHours(19);
//set times to EST. (UTC -5)
currentTime.setHours(currentTime.getHours() - 5);
startTime.setHours(startTime.getHours() - 5);
endTime.setHours(endTime.getHours() - 5);
//code to determine your variables goes here
var mylink = "https://mylink.com";
var windowname = "Chat Client";
if (currentTime < endTime && currentTime > startTime) {
popup(mylink, windowname);
}
});
function popup(mylink, windowname)
{
if (! window.focus)return true;
var href;
if (typeof(mylink) == 'string')
href=mylink;
else
href=mylink.href;
window.open(href, windowname, 'width=470,height=700,scrollbars=yes');
return false;
}
</SCRIPT>
//bad code removed to save space
EDIT:
To work in any timezone:
//bad code removed to save space
UPDATED:
Added jquery tags and function definition to demonstrate code structuring as per request.
UPDATE2:
$(document).ready(function() {
var currentTime = toUTC(new Date());
var startTime = toUTC(new Date());
var endTime = toUTC(new Date());
startTime.setHours(11);
startTime.setMinutes(0);
startTime.setSeconds(0);
endTime.setHours(19);
endTime.setMinutes(0);
endTime.setSeconds(0);
//set times to EST. (UTC -4)
currentTime.setHours(currentTime.getHours() - 4);
//code to determine your variables goes here
//var mylink =
//var windowname =
if (currentTime < endTime && currentTime > startTime) {
popup();
}
});
function popup() {
//put function code here
$('body').append("Here is some text");
}
function toUTC(inDate) {
inDate.setMinutes(inDate.getMinutes() + inDate.getTimezoneOffset());
return inDate;
}
And here it is in a fiddle.
But it's only work with local time.
var date = new Date();
var hours = date.getHours();
if(hours > 11 && hours < 19)
{
// show pop-up
}
Related
Problem is my timer was working as well. But when i save timers value to localStorage. I just want to when user refresh timer wont stop and resume when stopped at.
javascript
function startTimer() {
var presentTime = document.getElementById('timer').innerHTML;
var timeArray = presentTime.split(/[:]+/);
var m = timeArray[0];
var s = checkSecond((timeArray[1] - 1));
if(s==59){m=m-1}
if(m<0){ document.myform.submit(); }
document.getElementById('timer').innerHTML =
m + ":" + s;
setTimeout(startTimer, 1000);
var startTime = document.getElementById("timer").value;
localStorage.setItem("startTime", startTime);
//alert(startTime);
}
function Dahin(){
var startTime = localStorage.getItem("startTime");
document.getElementById('timer').value = startTime;
}
in my view
<h3 onload="Dahin();" class="page-title">Шалгалтын 50 асуулт</h3><h4><div>Үлдсэн хугацаа = <span id="timer">{{ $time }}</span></div></h4>
Update fixed timer
now how to save timer value to sessionstorage and retrieve when refresh page
Let change your code:
var check = localStorage.getItem("startTime");
var startTime = check ? check : document.getElementById("timer").innerHTML;
document.getElementById('timer').value = startTime;
function Dahin(){
localStorage.setItem("startTime", startTime);
}
the problem why you get null is because you use .value. You put your time into span tag. .value is only work for input field
I have been trying to make a timer disappear when it reaches 00:00 but everytime I try something it just hides the div right away.
Here is the code I am using:
$(document).ready(function(e) {
var $worked = $("#worked");
function update() {
var myTime = $worked.html();
var ss = myTime.split(":");
var dt = new Date();
dt.setHours(0);
dt.setMinutes(ss[0]);
dt.setSeconds(ss[1]);
var dt2 = new Date(dt.valueOf() - 1000);
var temp = dt2.toTimeString().split(" ");
var ts = temp[0].split(":");
$worked.html(ts[1] + ":" + ts[2]);
setTimeout(update, 1000);
}
setTimeout(update, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="worked">00:10</div>
I have created an example for you. For this example I have changed the timer's interval to 10ms so you can see the result quicker. Also instead of setting a setTimeout to run update inside the function update. You can use setInterval. I have also added a check inside the update function that checks if the time is 00:00. If it is true, then it invalidates the interval by calling clearInterval(timer); and runs $worked.hide()
$(document).ready(function (e) {
var $worked = $("#worked");
var timer = setInterval(update, 10);
function update() {
var myTime = $worked.html();
var ss = myTime.split(":");
var dt = new Date();
dt.setHours(0);
dt.setMinutes(ss[0]);
dt.setSeconds(ss[1]);
var dt2 = new Date(dt.valueOf() - 1000);
var temp = dt2.toTimeString().split(" ");
var ts = temp[0].split(":");
$worked.html(ts[1]+":"+ts[2]);
$worked.html(ts[1]+":"+ts[2]);
if(ts[1] === '00' && ts[2] === '00') {
clearInterval(timer);
$worked.hide();
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="worked">01:00</div>
Here's another approach :)
$(document).ready(function(e) {
var $worked = $("#timer");
var startTime = new Date().getTime();
var now, currentDistance;
setInterval(function update() {
now = new Date().getTime();
currentDistance = 10000 - now + startTime;
if (currentDistance > 0) {
$worked.html(parseInt(currentDistance / 1000) + " seconds, " + (currentDistance % 1000) + " ms left!");
} else {
$worked.hide();
}
}, 1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="timer" style="background-color: rgb(190, 190, 220); width: 200px; text-align: center"></div>
The basic premise of this is to have a section of code that changes a image based on a set schedule (in this case 9am to 5pm), sort of like an open and closed sign.
The code I have so far is:
<script type='text/javascript'>
$(window).load(function(){
// Translate your hours to UTC, example here is using Central Standard Time (-0500 UTC)
// Opening hour in UTC is 16, Closing hour is 0 the next day
var d = new Date(),
open = new Date(),
closed = new Date();
// Statically set UTC date for open
open.setUTCHours(16);
open.setUTCMinutes(0);
open.setUTCSeconds(0);
open.setUTCMilliseconds(0);
// Statically Set UTC date for closing
closed.setUTCDate(d.getUTCDate()+1); // UTC time rotates back to 0 so we add a day
closed.setUTCHours(0); // UTC hours is 0
closed.setUTCMinutes(0);
closed.setUTCSeconds(0);
closed.setUTCMilliseconds(0);
// Debugging
console.log("user's date:" + d);
console.log("store open time in user's timezone:" + open);
console.log("store close time in user's timezone:" + closed);
console.log(d > open); // user's time is greater than opening time
console.log(d < closed); // is user's time less than closing time (you don't have to go home...)
// Test for store open?
if (d > open && d < closed) {
setOpenStatus(true);
}
else {
setOpenStatus(false);
}
function setOpenStatus(isOpen) {
$('#open').toggle(isOpen);
$('#closed').toggle(!isOpen);
}
});//]]>
</script>
</head>
<body>
<div id="status">
<div id="open"><span title="OPEN"></span></div>
<div id="closed"><span title="CLOSED"></span></div>
</div>
</body>
</html>
How ever for some reason it is not changing at those times, I think it might have something to do with it not refreshing with the browser time but I'm not sure.
Thank you for any help you can give me!
In your HTML you need to add a symbols for open/close. I used the symbols + and - inside the span tag.
If you want to test the value each hour you have to use the javascript function setInterval and to stop this process you can use the function clearInterval.
// the intervalId
var nIntervId = null;
// for debug purposes
var lastIsOpen = true;
function setOpenStatus(isOpen) {
$('#open').toggle(isOpen);
$('#closed').toggle(!isOpen);
}
// the function to stop the setInterval function
function stopCheckIfClosed() {
if (nIntervId != null) {
clearTimeout(nIntervId);
nIntervId = null;
}
}
// your code:
// I added an optional parameter so that if you call this function
// without the parameter the value false is used, otherwise
// the value passed to the function is used
function checkIfClosed(isInDebugMode) {
var inDebugMode = isInDebugMode || false;
if (inDebugMode) {
if (lastIsOpen) {
lastIsOpen = false;
setOpenStatus(true);
} else {
lastIsOpen = true;
setOpenStatus(false);
}
nIntervId = window.setTimeout(checkIfClosed, 3000, true);
return;
}
var d = new Date();
// Test for store open?
if (d.getHours() >= 9 && d.getHours() <= 17) {
setOpenStatus(true);
// wait for the 17
nIntervId = window.setTimeout(checkIfClosed, (17 - 9)*60*60*1000, true);
} else {
setOpenStatus(false);
// wait for the 9
nIntervId = window.setTimeout(checkIfClosed, (17 - 9)*60*60*1000, true);
}
}
$(function () {
// on document ready call your function: with no arguments means no debug
checkIfClosed(true);
// compute if wait for the next 9 or 17
var d = new Date();
var tomorroAtNine = new Date(d.getFullYear(), d.getMonth(), d.getDate() + 1, 9);
var tomorroAtFive = new Date(d.getFullYear(), d.getMonth(), d.getDate() + 1, 17);
var diffToNine = (tomorroAtNine.getTime() - d.getTime()) * 1000;
var diffTofive = (tomorroAtFive.getTime() - d.getTime()) * 1000;
if (diffToNine < diffTofive) {
//nIntervId = window.setTimeout(checkIfClosed, diffToNine, true);
} else {
//nIntervId = window.setTimeout(checkIfClosed, diffTofive, true);
}
// for test pursposes I reduced the interval to 3 seconds
nIntervId = window.setTimeout(checkIfClosed, 1000, true);
});
#status div {
font-family:helvetica,arial,sans-serif;
font-size:20px;
font-weight:bold;
}
#status span {
display:inline-block;
text-indent:-12000px;
}
#open,#closed{
display:none;
}
#open span {
background-image: url('http://i.imgur.com/KmGlJgN.png');
width:640px;
height:335px;
}
#closed span {
background-image: url('http://i.imgur.com/YWLrDlm.png');
width:1100px;
height:850px;
}
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<div id="status">
<div id="open"><span title="OPEN">+</span></div>
<div id="closed"><span title="CLOSED">-</span></div>
</div>
I want to make a countdown timer, that can be used on several places in the same page - so I think it should be a function in some way.
I really want it to be made with jQuery, but I cant quite make it happen with my code. I have e.g. 10 products in a page, that I need to make a countdown timer - when the timer is at 0 I need it to hide the product.
My code is:
$(document).ready(function(){
$(".product").each(function(){
$(function(){
var t1 = new Date()
var t2 = new Date()
var dif = t1.getTime() - t2.getTime()
var Seconds_from_T1_to_T2 = dif / 1000;
var Seconds_Between_Dates = Math.abs(Seconds_from_T1_to_T2);
var count = Seconds_Between_dates;
var elm = $(this).attr('id');
alert(elm);
countdown = setInterval(function(){
$(elm + " .time_left").html(count + " seconds remaining!");
if (count == 0) {
$(this).css('display','none');
}
count--;
}, 1000);
});
});
});
EDIT 1:
$(document).ready(function(){
$(".product").each(function(){
var elm = $(this).attr('id');
$(function(){
var t1 = new Date()
var t2 = new Date()
var dif = t1.getTime() - t2.getTime()
var Seconds_from_T1_to_T2 = dif / 1000;
var Seconds_Between_Dates = Math.abs(Seconds_from_T1_to_T2);
var count = Seconds_Between_dates;
alert(elm);
countdown = setInterval(function(){
$(elm + " .time_left").html(count + " seconds remaining!");
if (count == 0) {
$(this).css('display','none');
}
count--;
}, 1000);
});
});
});
Do you have any solutions to this?
I'd probably use a single interval function that checks all the products. Something like this:
$(function() {
/* set when a product should expire.
hardcoded to 5 seconds from now for demonstration
but this could be different for each product. */
$('.product').each(function() {
$(this).data('expires', (new Date()).getTime() + 5000);
});
var countdown_id = setInterval(function() {
var now = (new Date()).getTime();
$('.product').each(function() {
var expires = $(this).data('expires');
if (expires) {
var seconds_remaining = Math.round((expires-now)/1000);
if (seconds_remaining > 0) {
$('.time-left', this).text(seconds_remaining);
}
else {
$(this).hide();
}
}
});
}, 1000);
});
You could also cancel the interval function when there is nothing left to expire.
Your problem seems to be that this doesn't refer to the current DOM element (from the each), but to window - from setTimeout.
Apart from that, you have an unnecessary domReady wrapper, forgot the # on your id selector, should use cached references and never rely on the timing of setInterval, which can be quite drifting. Use this:
$(document).ready(function(){
$(".product").each(function(){
var end = new Date(/* from something */),
toUpdate = $(".time_left", this);
prod = $(this);
countDown();
function countdown() {
var cur = new Date(),
left = end - cur;
if (left <= 0) {
prod.remove(); // or .hide() or whatever
return;
}
var sec = Math.ceil(left / 1000);
toUpdate.text(sec + " seconds remaining!"); // don't use .html()
setTimeout(countdown, left % 1000);
}
});
});
I'm having a problem with this JavaScript script. I've tried a number of things to get it to work. The alerts in there at current are there for debugging purposes, and seem to be failing to occur.
Help please?
function checkTime(this_time){
var the_string = "checkTime("+this_time+")";
var now = ((new Date()).getTime());
if(parseInt(now) >= parseInt(this_time)){
document.write("TIMEUP!");
}
alert(now);
alert(this_time);
var t = setTimeout(the_string,300);
}
var the_time = (((new Date()).getTime())+19000);
var the_string = "checkTime("+the_time+")";
var t = setTimeout(the_string,300);
Thanks,
Will.
Seems like you're looking for a countdown?
See this fiddle. The code is simplified to:
var bench = 19000 + new Date().getTime(),
timer = setInterval(
function(){
checkTime(bench);
}
, 1000
);
function checkTime(this_time){
var check = new Date - this_time;
if(check>=0){
alert('time\'s up!');
clearInterval(timer);
}
}
You should use setTimeout with closures instead of strings.
var now = new Date().getTime();
setTimeout(function(){
//your Javascript code here
//"now" can be used here as a closure
}, 300);
Here is a safer and self-contained version. A document.write after load will clear the page completely
http://jsfiddle.net/mplungjan/Zt5k7/
window.onload=function() {
var timer = function (endTime) {
var end = new Date(endTime);
var tId;
this.checkTime=function(){
var now = new Date();
document.getElementById("msg").innerHTML=now.toLocaleString();
if (now.getTime()>=end.getTime()) {
document.getElementById("msg").innerHTML="TIME's UP!";
clearInterval(tId);
}
}
tId = setInterval(this.checkTime,300);
}(new Date().getTime()+5000);
}
or for a proper countdown http://jsfiddle.net/mplungjan/Zt5k7/1/
window.onload=function() {
var timer = function (endTime) {
var end = new Date(endTime);
var tId;
this.checkTime=function(){
var now = new Date();
document.getElementById("msg").innerHTML=now.toLocaleString();
var diff = end.getTime()-now.getTime()
if (diff >= 1) document.getElementById("msg").innerHTML=parseInt(diff/1000)+1;
else {
document.getElementById("msg").innerHTML="TIME's UP!";
clearInterval(tId);
}
}
tId = setInterval(this.checkTime,300);
}(new Date().getTime()+9000);
}
I suppose the code could be made more simple to work.
function checkTime(this_time){
var now = ((new Date()).getTime());
if((now - this_time) >= 0){
document.write("TIMEUP!");
window.clearInterval(timer);
}
}
var t_t = (((new Date()).getTime())+19000);
var timer = window.setInterval(function(){
checkTime(t_t); }
, 300);
Cheers!