I'm trying to make a welcome message for the user.
My planning is:
if the user visits the first time the page then show a div message after 30 sec.;
if the user already visited the page there is no need to show div message.
I have writed this code:
My cookies code
<script type="text/javascript">
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
} else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
</script>
My display code
<script type="text/javascript">
function showbox() {
document.getElementById("apDiv1").style.visibility = "visible";
}
setTimeout("showbox()", 30000); // after 5 secs
</script>
<script type="text/javascript">
if (!readCookie('visitedPreviously')) {
showbox();
//document.write(' Your Message Goes Here And You See It Only Once ');
createCookie('visitedPreviously', 'visitedPreviously', 3); // 365 days persistence
}
//eraseCookie('visitedPreviously'); // FOR TEST PURPOSES
</script>
My problem is when a visitor visits the page first time, the div shows immediately (30 sec.) - Doesn't work
But when a returning visitor visits again the page the div shows after 30 sec.
I want for a first time user visit to show a div message after 30 sec.
Please help me.
According to your explanation you want to show a dialog after 30 seconds only to new user. So you need to change your code into below:
<script type="text/javascript">
function showbox() {
document.getElementById("apDiv1").style.visibility = "visible";
}
if (!readCookie('visitedPreviously')) { //if he/she is a new user
setTimeout("showbox()", 30000); // after 30 secs
//document.write(' Your Message Goes Here And You See It Only Once ');
createCookie('visitedPreviously', 'visitedPreviously', 3); // 365 days persistence
}
//eraseCookie('visitedPreviously'); // FOR TEST PURPOSES
</script>
You need to remove quotes around showbox.
This the syntax of the setTimeout fnction,
setTimeout(function,milliseconds,param1,param2,...)
setTimeout expects the first parameter to be a function call.
function showbox() {
document.getElementById("apDiv1").style.visibility = "visible";
alert();
}
setTimeout(showbox, 30000); // after 5 secs
if (!readCookie('visitedPreviously')) {
//I added a set timeout here which is what you need
setTimeout(showbox, 30000); // after 5 secs
//document.write(' Your Message Goes Here And You See It Only Once ');
createCookie('visitedPreviously', 'visitedPreviously', 3); // 365 days persistence
}
//eraseCookie('visitedPreviously'); // FOR TEST PURPOSES
Remove the quote and the brackets in the "showbox()". Like this:
setTimeout(showbox, 30000);
I've corrected your code below, you had the setTimeout being called before the cookie had been checked!
function showbox() {
document.getElementById("apDiv1").style.visibility = "visible";
}
if (!readCookie('visitedPreviously')) {
setTimeout("showbox()", 30000); // after 30 seconds
//document.write(' Your Message Goes Here And You See It Only Once ');
createCookie('visitedPreviously', 'visitedPreviously', 3); // 365 days persistence
}
Please try it out.
You don't need quotes around showbox:
setTimeout(showbox, 30000);
Docs: https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout
You should modify your display code to:
<script type="text/javascript">
function showbox() {
document.getElementById("apDiv1").style.visibility = "visible";
}
setTimeout(showbox, 30000); // after 5 secs
</script>
<script type="text/javascript">
if (!readCookie('visitedPreviously')) {
//I added a set timeout here which is what you need
setTimeout(showbox, 30000); // after 5 secs
//document.write(' Your Message Goes Here And You See It Only Once ');
createCookie('visitedPreviously', 'visitedPreviously', 3); // 365 days persistence
}
//eraseCookie('visitedPreviously'); // FOR TEST PURPOSES
</script>
Please note the change is made above is:
//I added a set timeout here which is what you need
setTimeout(showbox, 30000); // after 5 secs
It is not a good practice to send a function as a string as you have done in the set timeout.
You need to modify your code to this
<script type="text/javascript">
function showbox() {
if (!readCookie('visitedPreviously')) {
document.getElementById("apDiv1").style.visibility = "visible";
//document.write(' Your Message Goes Here And You See It Only Once ');
createCookie('visitedPreviously', 'visitedPreviously', 3); // 365 days
}
//eraseCookie('visitedPreviously'); // FOR TEST PURPOSES
}
setTimeout(showbox, 30000); // after 5 secs
</script>
Related
I am a beginner in javascript. There is a countdown timer in javascript, in which i wan to include a automatic form submit after duration ends. How can I do it? Please help me. The code is given bellow.
<script>
function countdown(minutes) {
var seconds = 60;
var mins = minutes;
function tick() {
var counter = document.getElementById("clockdiv");
var current_minutes = mins-1;
seconds--;
var minutesSpan = counter.querySelector('.minutes');
var secondsSpan = counter.querySelector('.seconds');
minutesSpan.innerHTML = current_minutes.toString();
secondsSpan.innerHTML = (seconds < 10 ? "0" : "") + String(seconds);
if( seconds > 0 ) {
setTimeout(tick, 1000);
} else {
if(mins > 1){
// countdown(mins-1); never reach “00″ issue solved:Contributed by Victor Streithorst
setTimeout(function () { countdown(mins - 1); }, 1000);
}
}
}
tick();
}
countdown(<?php echo $duration?>);
</script>
if(mins==0 && seconds==0){
form=document.getElementsByTagName("form")[0];
form.submit();
}
Add this into the countdown function.
If both minutes and seconds are 0 submit the first form found in your html.
As already shown on Stack Overflow:
How to set a timer using jQuery to sent HTTP post data of HTML form
You could use jQuery (include it in head tag):
setTimeout(function() { $('#form').submit(); }, 5000);
Where your form has id="form" and the delay is of 5s.
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 was wondering how can I stop a timer after ten seconds in javascript using setInterval and clearInterval??
Here's my code example, could you please tell me where I'm going wrong:
<!DOCTYPE html>
<html>
<head>
<script>
var tt=setInterval(function(){startTime()},1000);
function startTime()
{
var today = new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
today=checkTime(today);
document.getElementById('txt').innerHTML=s;
}
function checkTime(tt)
{
if (tt==10)
{
tt="0" + tt;
console.log(tt);
clearInterval(tt);
}
return tt;
}
</script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>
you can set timeout on clear like this right after you set the interval:
var tt = setInterval(function(){ startTime() }, 1000);
setTimeout(function() { clearInterval(tt); }, 10000);
Since startTime() will run every second, make a counter to increment to 10 inside of it, then clear the interval.
var tt=setInterval(function(){startTime()},1000);
var counter = 1;
function startTime()
{
if(counter == 10) {
clearInterval(tt);
} else {
counter++;
}
document.getElementById('txt').innerHTML= counter;
}
JSFiddle
Because you named a local variable named tt which does not let you access the global variable tt. Very bad planning on variable names.
Your code also will not stop at 10 seconds, it will stop when the time is at 10 seconds or 10 minutes.
function checkTime(xtt)
{
if (xtt==10)
{
xtt="0" + xtt;
console.log(xtt);
clearInterval(tt);
}
return xtt;
}
This works for me.
var tt = setInterval(function(){ startTime() }, 1000);
setTimeout(function() { clearInterval(tt); }, 10000);
you can do that
setInterval(startTime, 1000).pipe(takeUntil(timer(10000)));
I'm sorry if this question is a bit tricky but I have no other way of asking it and I am an absolute noob in javascript world.
I have this javascript counter that someone helped me to gather on stackoverflow and it works fine BUT
the countdown timer will start from the beginning on a different browsers.
i.e. when I look at it on Firefox, it will carry on counting down and it will keep working as it should. lets say the timer is set to countdown a day. on Firefox it will show 23:24 hours/minutes left but if I open a new browser (any browser), it will show the timer 23:59 hours/minutes left and it will start counting down from there... even though the countdown timer was already running on the same page!!
here is the code:
<script type="text/javascript">
var EXPIRY = parseInt(new Date().getTime()/1000) + 24*60*60;
var counter = null;
var counter_interval = null;
function setCookie(name,value,days) {
console.log("setting "+name+" "+value);
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires="+date.toGMTString();
}
else {
expires = "";
}
document.cookie = name+"="+value+expires+"; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1,c.length);
}
if (c.indexOf(nameEQ) === 0) {
return c.substring(nameEQ.length,c.length);
}
}
return null;
}
function deleteCookie(name) {
setCookie(name,"",-1);
}
function resetCounter() {
EXPIRY = parseInt(new Date().getTime()/1000) + 24*60*60;
}
function stopCounter() {
window.clearInterval(counter_interval);
deleteCookie('Expiry');
}
function updateCounter() {
var msg = '';
curTime = parseInt(new Date().getTime()/1000);
if (curTime < EXPIRY) {
msg = convertSecondsToDays(EXPIRY - curTime);
}
else {
EXPIRY = parseInt(new Date().getTime()/1000) + 24*60*60;
}
var el = document.getElementById('counter');
if (el) {
el.innerHTML = msg
}
}
function convertSecondsToDays(sec) {
var days, hours,rem,mins,secs;
days = parseInt(sec/(24*3600));
rem = sec - days*3600
hours = parseInt(rem/3600);
rem = rem - hours*3600;
mins = parseInt(rem/60);
secs = rem - mins*60;
return days +":" + hours +":"+mins + ":"+ secs + "";
}
function startCounter() {
stopCounter();
setCookie('Expiry', EXPIRY, 1);
counter_interval = window.setInterval(updateCounter, 1000);
}
function init() {
EXPIRY = getCookie('Expiry');
if (!EXPIRY) {
console.log("unable to find cookie");
resetCounter();
}
startCounter();
}
init();
</script>
you can view it on the fiddle here: http://jsfiddle.net/h2DEr/1/
how can i make it in a way that it will show the same time left on all the browsers as it will be displayed on the same page?
Thanks
Edit:
I found this code which works with mysql. it works fine but instead of counting down it will show how many days/hours/minutes the product/item was posted on the site. and this doesn't need any javascript as is...
This is sort of what I am looking for but instead of counting up it needs to countdown:
<?php
//list fields and convert to seconds
$countdown['days']=(5) * 24 * 60 * 60;
$countdown['hours']=(3) * 60 * 60;
// etc, etc
$countsum=time() + $countdown['days'] + $countdown['hours']; //and so on
// the above would be the timestamp to enter into the table
##########
// 'dumbed down' query
include "config/connect_to_mysql.php";
$result=mysql_query("SELECT * FROM tomProduct WHERE id='id';");
while ($row=mysql_fetch_assoc($result))
$time=$row['date_added'] - time(); //this field would be a PHP timestamp (time())
$count=getdate($time);
$x=getdate(); //todays information
$count['mday'] -= $x['mday'];
$count['hour'] -= $x['mday'];
$count['minutes'] -= $x['minutes'];
echo "$count[mday] Days $count[hour] Hours $count[minutes] Minutes"; //etc
// untested, but should work
?>
JavaScript is always running on the client. One instance of the timer has no knowledge of any other instance running elsewhere.
To synchronize time between different browsers, you would need server-side scripts.
Using expiration-time-stamps in a server-side script in conjunction with JavaScript timers should give you the synchronization you are looking for.
Cookies are not transferred from browser to browser. They are stored in the web browser.
Now that I was helped getting AJAX running just great, I'm having problems running a clock function with it....
Clock code (located in the head):
<script type="text/javascript">
var ampm = "AM"; //Default
var message="";
function startTime()
{
var today = new Date(); //Number goes here
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
h=checkTime2(h);
document.getElementById('clocktxt').innerHTML=h+":"+m+":"+s+ " " +ampm + " " + message;
//t=setTimeout('startTime()',500);
}
function checkTime(i)
{
if (i<10)
{
i="0" + i;
message = "How long you gonna sit there?";
}
return i;
}
function checkTime2(i)
{
if (i>12)
{
i=i-12;
ampm="PM";
}
return i;
}
//setInterval(startTime,1000);
</script>
AJAX code (bottom of the document):
<script type='text/javascript'>
function CheckForChange(){
//alert("<?echo (count($listArray)) . ' and ' . count(file($filename_noformat))?>");
//if (<?echo count($listArray)?> == <?echo count(explode("\n", $filename_noformat))?>){
//setInterval("alert('Yup, it is 1')", 5000);
//alert('Now it is changed');
//}
var ajaxReady = new XMLHttpRequest();
ajaxReady.onreadystatechange = function(){
if (ajaxReady.readyState == 4){
//Get the data
//document.getElementById('clocktxt').innerHTML = ajaxReady.responseText;
//startTime();
//alert("here");
//alert(ajaxReady.responseText);
}
}
ajaxReady.open("GET","ServerTime.php",true);
ajaxReady.send(null);
}
setInterval(CheckForChange(), 1000);
setInterval(startTime(),1000);
</script>
What I'm trying to do is pass the input from ServerTime.php which is just a count of milliseconds from Unix epoch, into the clock, so the clock is being updated by the AJAX every second and the clock function runs with a new starting value each second.... I used to have parameters for the clock function before I realized the clock wasn't even getting called.
What do you think is wrong? I'm guessing it has something to do with the clock and the caller of the clock being in two different script tags, but I can't think of how to get around it. For some reason when I moved the AJAX part into the same script tag, following the clock, nothing happens.
To Kolink: I have this
function getTheNow(){
TIMESTAMP = <?php echo time(); ?>000;
offset = new Date().getTime()-TIMESTAMP;
setInterval(function() {
var now = new Date();
now.setTime(now.getTime()-offset);
// print out the time according to the variable `now`
//alert(now);
},5000);
return now;
}
function startTime()
{
var now = getTheNow;
//alert(now);
var today = new Date(); //Number goes here
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
h=checkTime2(h);
document.getElementById('clocktxt').innerHTML=h+":"+m+":"+s+ " " +ampm + " " + message;
t=setTimeout('startTime()',500);
}
function checkTime(i)
{
if (i<10)
{
i="0" + i;
message = "How long you gonna sit there?";
}
return i;
}
function checkTime2(i)
{
if (i>12)
{
i=i-12;
ampm="PM";
}
return i;
}
setInterval(startTime,1000);
Computer clocks are not so inaccurate that you have to re-sync them every second. Try every ten minutes, or even every hour.
In fact, I just do away with synchronising altogether. It is far easier to do this:
<script type="text/javascript">
TIMESTAMP = <?php echo time(); ?>000;
offset = new Date().getTime()-TIMESTAMP;
setInterval(function() {
var now = new Date();
now.setTime(now.getTime()-offset);
// print out the time according to the variable `now`
},1000);
</script>
JavaScript 101 error
setInterval(CheckForChange(), 1000);
setInterval(startTime(),1000);
You are not assigning the function, you are calling/executing them and saying what ever is returned from these functions should be set. Drop the () so you are referencing the functions.
setInterval(CheckForChange, 1000);
setInterval(startTime,1000);