I am currently trying to fill a html table with several counters, one underneath the other, to show days past since an incident.
Thanks to the internet, i ended up with this script:
<script language="JavaScript1.2" type="text/javascript">function
setcountup(theyear,themonth,theday){
yr=theyear;mo=themonth;da=theday
}
//////////CONFIGURE THE countup SCRIPT HERE//////////////////
//STEP 1: Configure the date to count up from, in the format year, month, day:
//This date should be less than today
setcountup(2012,9,19)
//STEP 2: Configure text to be attached to count up
var displaymessage=""
//STEP 3: Configure the below 5 variables to set the width, height, background color,
and text style of the countup area
var countupwidth='90%'
var countupheight='40px' //applicable only in NS4
var countupbgcolor=''
var opentags='<font face="Verdana"><large>'
var closetags='</large></font>'
//////////DO NOT EDIT PASS THIS LINE//////////////////
var montharray=new
Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")
var crosscount=''
function start_countup(){
if (document.layers)
document.countupnsmain.visibility="show"
else if (document.all||document.getElementById)
crosscount=document.getElementById&&!document.all?
document.getElementById("countupie") : countupie
countup()
}
if (document.all||document.getElementById)
document.write('<span id="countupie" style="width:'+countupwidth+'; background-
color:'+countupbgcolor+'"></span>')
window.onload=start_countup
function countup(){
var today=new Date()
var todayy=today.getYear()
if (todayy < 1000)
todayy+=1900
var todaym=today.getMonth()
var todayd=today.getDate()
var todayh=today.getHours()
var todaymin=today.getMinutes()
var todaysec=today.getSeconds()
var todaystring=montharray[todaym]+" "+todayd+", "+todayy+"
"+todayh+":"+todaymin+":"+todaysec
paststring=montharray[mo-1]+" "+da+", "+yr
paststring="10:00"+montharray[mo-1]+" "+da+", "+yr
dd=Date.parse(todaystring)-Date.parse(paststring)
dday=Math.floor(dd/(60*60*1000*24)*1)
dhour=Math.floor((dd%(60*60*1000*24))/(60*60*1000)*1)
dmin=Math.floor(((dd%(60*60*1000*24))%(60*60*1000))/(60*1000)*1)
dsec=Math.floor((((dd%(60*60*1000*24))%(60*60*1000))%(60*1000))/1000*1)
if (document.layers){
document.countupnsmain.document.countupnssub.document.write(opentags+dday+ " days
"+displaymessage+closetags)//to get more detail, enter one of the following in the
write line(also in the else): +dhour+" hours, "+dmin+" minutes, and "+dsec+" seconds
"
document.countupnsmain.document.countupnssub.document.close()
}
else if (document.all||document.getElementById)
crosscount.innerHTML=opentags+dday+ " days "+displaymessage+closetags//+dhour+"
hours, "+dmin+" minutes, and "+dsec+" seconds "
setTimeout("countup()",1000)
}
</script>
Now, each cell row has a counter for a different event.
I seem to be incapable of just putting this code in each , as it creates a conflict (i think)
I am completely new at this, and i have to get this sorted out.
Can anybody help me out, or point me in the right direction please?
Thank you in advance
I spent a good amount of time trying to get the code you posted to work, and I have to say, that's some really bad code. There's a lot of unneeded code like:
paststring=montharray[mo-1]+" "+da+", "+yr
paststring="10:00"+montharray[mo-1]+" "+da+", "+yr
and a lot of just general formatting craziness. I believe I'd made it work and it's significantly easier to read than it was. This fiddle should help you make yours work.
http://jsfiddle.net/9DNaD/
Related
I have a js timer that is used to show a countdown to the end times on items that are sold in an auction format. The js I use is below.
$('[data-countdown]').each(function() {
var $this = $(this), finalDate = $(this).data('countdown');
$this.countdown(finalDate, function(event) {
$this.html(event.strftime('%-Dday%!D %-Hhr%!H %Mmin%!M %Ssec'));
});
});
I want to make this timezone aware so I searched online and found MomentJS.
I've included the moment-with-locales.min.js and moment-timezone-with-data-2010-2020.min.js files and they are being correctly loaded.
I'm really struggling to get my head around how to integrate the js into my current script as the sample on the github is for a single instance timer only.
The code example they give is
var nextYear = moment.tz("2015-01-01 00:00", "America/Sao_Paulo");
$('#clock').countdown(nextYear.toDate(), function(event) {
$(this).html(event.strftime('%D days %H:%M:%S'));
});
Now I assume I need to apply the
= moment.tz("2015-01-01 00:00", "America/Sao_Paulo");
type code to my date which are stored in data-countdown, but I just end up with a blank space where the countdown should be.
This is what I tried to do
var $this = $(this), finalDate = moment.tz($(this).data('countdown'), "America/Sao_Paulo");
Where have I gone wrong adding the moment.tz command?
I got it to work using
$('[data-countdown]').each(function() {
var $this = $(this), finalDate = moment.tz($(this).data('countdown'), "Europe/London");
$this.countdown(finalDate.toDate(), function(event) {
$this.html(event.strftime('%-Dday%!D %-Hhr%!H %Mmin%!M %Ssec'));
});
});
Only issue I have is that the time is 1hr out. An end time of 15:00 in London should have one hour more on the countdown in Paris, but it has two hours more at the moment.
Okay the questions are. I need help on making it so when I click the button it runs the free_cash variable in the function which I have set up. But I want it to add the givin amount to the total money the person has.
I also want to know how I can make it so when you click the button to get your free daily cash it only allows you to do it once a day and if you click it more the message switches to Something like you already been givin a handout today.
<!DOCTYPE html>
<html>
<head>
<title>
Character
</title>
<style>
</style>
</head>
<body>
<p style="margin-right: 20px; margin-left: 20px; margin-top: 5px; color: darkblue; font-size: 35px;">Money:</p>
<button onclick="FreeCash()">Free Daily Cash</button><br>
<p id="freecash"></p>
<script>
function FreeCash(){
var free_cash = "Someone handed you \"$100\" You must be a lucky man";
var nofree_cash = "Sorry you already got your handout for the day. Come back tomorrow ight.";
document.getElementById("freecash").innerHTML = free_cash;
}
</script>
<br><br><br><br>
<noscript>
<h3>This site requires JavaScript</h3>
</noscript>
</body>
</html>
You should do something like this:
function FreeCash() {
//Checks whether lastDate has been set.
if (!!localStorage.getItem("lastDate")) {
//If so and a day did not pass since then, then end the function
if ((new Date() - new Date(localStorage.getItem("lastDate"))) / (1000 * 3600 * 24) < 1) {
return;
}
}
//Set last date to current moment. You can set it to 00:00:00 of the day as well, if that fulfills your requirements better.
localStorage.setItem("lastDate", new Date());
var free_cash = "Someone handed you \"$100\" You must be a lucky man";
var nofree_cash = "Sorry you already got your handout for the day. Come back tomorrow ight.";
document.getElementById("freecash").innerHTML = free_cash;
}
This should solve the problem on client-side even if the user navigates off the page, however, you need a validation at server-side as well, because I could modify your client-side functions in my browser console whenever I want to do so.
You can use a variable to check if the button was clicked :
var clicked = false;
function FreeCash(){
var free_cash = "Someone handed you \"$100\" You must be a lucky man";
var nofree_cash = "Sorry you already got your handout for the day. Come back tomorrow ight.";
if(!clicked) {
document.getElementById("freecash").innerHTML = free_cash;
clicked = true;
} else {
document.getElementById("freecash").innerHTML = nofree_cash;
}
}
You can see the DEMO here.
EDIT:
And to make it available once a day you could use a setInterval() to reset the value of clicked to false after a day.
setInterval(function(){
clicked = false;
}, 1000*60*60*24); // after a day
It's a dirty way but it should do the trick.
You can see the updated fiddle wich executes every 10 seconds.
try this
var givenDateTime = new Date();
var isGiven = false;
function FreeCash(){
var cuurDateTime = new Date();
var message = '';
var free_cash = "Someone handed you \"$100\" You must be a lucky man";
var nofree_cash = "Sorry you already got your handout for the day. Come back tomorrow ight.";
alert(isGiven);
alert((cuurDateTime.getDate() - 1) < givenDateTime);
if(isGiven && (cuurDateTime.getDate() - 1) < givenDateTime){
message=nofree_cash;
document.getElementById("freecash").innerHTML = message;
}else{
message=free_cash;
isGiven = true;
givenDateTime = new Date();
document.getElementById("freecash").innerHTML = message;
}
}
You cannot do this with only javascript.... you need a database to store the time when your user clicked, tough a web side language (PHP, Java EE....ect).
I am terrible with Javascript but learning from my bruises.
On the site I am working on - I currently have a page setup for everyday of the year (i.e. January 1st has its own page '01-jan-01.html' January 2nd is '01-jan-02.html') - I want to make a button that will look up the current date then send the user to the corresponding page (Think 'This day in history').
I already have a button that will pick one of these pages at random and the code works see below:
<script type="text/javascript">
var urls = [
'01-jan-01.html'
'01-jan-02.html'
....
];
function goSomewhere() {
var url = urls[Math.floor(Math.random()*urls.length)];
window.location = url; // redirect
}
Then on my button I simply call goSomewhere() on the onClick() and as i said earlier, this works fine. However I can't figure out how to select based on the CURRENT DATE. any help would be greatly appreciated. thank you!
EDIT: No answers but here is the progress so far:
<script>
var day = date.getDate();
var month = date.getMonth();
function goSomewhere() {
var url = month + "-" + day];
window.location = url; // redirect
}
</script>
This wouldn't even solve my problem entirely but its how I'm trying to wrap my head around the logic. In the above code I would still need to find a way to incorporate the 'jan' (month) varible in each webpage link since the formatting is 'MM-mmmmm-DD' - would it be easier if I change the naming mechanic to simply "MM-DD"? I'd prefer not to since it would involve a lot of manual work. Thanks
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;
var yyyy = today.getFullYear();
var yy = yyyy.toString().substr(2,2); //get two digit year
if(dd<10){ dd='0'+dd }
if(mm<10){ mm='0'+mm }
location.href = yy+'-'+mm+'-'+dd+'.html';
i was wondering if there is a quite simple solution to display content between certain hours and only during working days in a Europe timezone?
The hours will be everyday (except weekends) between 9AM and 5PM, between those times a html content should be shown.
If possible a different html content from 5PM till 9AM.
The short version is that you use new Date() to get the current date/time, and then you use DOM manipulation to add/remove that content as appropriate. If you want content to change in-between page loads, you'll probably also want a window.setInterval running to update things constantly.
You might want to check out the Moment.js library (http://momentjs.com/), as it has a number of functions which make working with dates/times easier.
Here's a quickie example (without using Moment) that just checks "are we past 5 or not?":
window.setInterval(function() {
if (new Date().getHours() > 17) { // if it's after 5pm (17:00 military time)
$('#someContent').hide();
} else {
$('#someContent').show();
}
}, 1000 * 60) // this will run every minute
With that hopefully you can figure out how to add the other needed if checks.
Here you go! :)
<html>
<head>
<script type="text/javascript">
var date=new Date();
var year=date.getFullYear();
var month=date.getMonth();
var day=date.getDate(); // fixed
function SetDivContent() {
var div=document.getElementById('date_dependent');
if (year==2010 && month==11) { // fixed (the JavaScript months order is 0-11, not 1-12)
if (day>=3 && day<11) { // the following content will be displayed 12/03/2010, 12/04/2010, [...], 12/09/2010, 12/10/2010
div.innerHTML='content 1';
}
else if (day==11 || day==12) { // this one will be displayed 12/11/2010 and 12/12/2010
div.innerHTML='content 2';
}
else if (day>12) { // this one - 12/13/2010 and later, until the end of December
div.innerHTML='content 3';
}
}
else if (year==2011 && month>=0) div.innerHTML='content 3'; // OPTIONAL - just to ensure that content 3 is displayed even after December.
}
</script>
</head>
<body onload="SetDivContent()">
<div id="date_dependent"></div>
</body>
</html>
answered Nov 30 '10 at 22:16
rhino
I'm using the following script and the later onclick-event. If I use the onclick my rotating banner loses it and starts displaying pictures at random intervals. I think I should override the "setTimeout" at the end of the first piece of code. Question is how exactly?
<script language="JavaScript" type="text/javascript">
<!--
var RotatingImage1_Index = -1;
var RotatingImage1_Images = new Array();
RotatingImage1_Images[0] = ["images/ban_image1.png","",""];
<!-- 15 Images in total-->
RotatingImage1_Images[14] = ["images/ban_image2.png","",""];
function RotatingImage1ShowNext(){
RotatingImage1_Index = RotatingImage1_Index + 1;
if (RotatingImage1_Index > 14)
RotatingImage1_Index = 0;
eval("document.RotatingImage1.src = RotatingImage1_Images[" + RotatingImage1_Index + "][0]");
setTimeout("RotatingImage1ShowNext();", 4000);}
// -->
</script>
<img src="images/ban_image1.png" id="ban_img1" name="RotatingImage1">
This part works as it should.
<div id="ban_next" align="left">
<a href="#" onclick="RotatingImage1ShowNext();return false;">
<img src="images/ban_next.png" id="ban_nxt1"></a></div>
This part works as well, but only correctly if I set the 'setTimeout' to '0'. I am sorry, I'm compleatly new to this. I was looking at this stackoverflow.com question, but I don't know how to implement that here.
I thank you in advance.
Edit:
The rotating image starts automaticly. It displays a new image every 4 seconds. The images have text on them, or better insider jokes. Readers should be tempted to read them, but if the automated rotation cought there antention, the have to keep that antention for a full minute to see all images. That's probably to long. So I thought to implement a button to overwrite the timer and show the next image 'on click'. But after the click the rotation-time should turn back to auto-rotation. That's the plan.
Thank you Prusse, for now it bedtime, I will try to grasp your answer tomorrow ;)
You don't need eval, just do document.RotatingImage1.src = RotatingImage1_Images[RotatingImage1_Index][0].
The described behavior happens because there is more then one timer firing. There is one set on the first time RotatingImage1ShowNext is called, more one each time its called from your onclick handler. To fix this declare a global for your timer and before another timeout is set clear it if set. Like:
var global_timerid;
function RotatingImage1ShowNext(){
//RotatingImage1_Index = RotatingImage1_Index + 1;
//if (RotatingImage1_Index > 14) RotatingImage1_Index = 0;
RotatingImage1_Index = (RotatingImage1_Index + 1) % RotatingImage1_Images.length;
//document.RotatingImage1.src = RotatingImage1_Images[RotatingImage1_Index][0];
document.getElementById('ban_img1').src = RotatingImage1_Images[RotatingImage1_Index][0];
if (global_timerid) clearTimeout(global_timerid);
global_timerid = setTimeout(RotatingImage1ShowNext, 4000);
}