How can I make my two JavaScripts work together? - javascript

Hello I am trying to have my clock and my countdown timer on the same page so people/users can see when I am done with my game and for them to have the correct time with the countdown timer also. Here is the code. They both work separately but when the are both put on a .php page only the bottom one (countdown timer) works and if I do JQuery.noconflict to the timer the clock works but the countdown doesn't.
<!-- Clock Part 1 - Holder for Display of Clock -->
<span id="tP"> </span>
<!-- Clock Part 1 - Ends Here -->
<!-- Clock Part 2 - Put Anywhere AFTER Part 1 -->
<script type="text/javascript">
// Clock Script Generated By Maxx Blade's Clock v2.0d
// http://www.maxxblade.co.uk/clock
function tS(){ x=new Date(); x.setTime(x.getTime()); return x; }
function lZ(x){ return (x>9)?x:'0'+x; }
function tH(x){ if(x==0){ x=12; } return (x>12)?x-=12:x; }
function dE(x){ if(x==1||x==21||x==31){ return 'st'; } if(x==2||x==22){ return 'nd'; } if(x==3||x==23){ return 'rd'; } return 'th'; }
function y2(x){ x=(x<500)?x+1900:x; return String(x).substring(2,4) }
function dT(){ window.status=''+eval(oT)+''; document.title=''+eval(oT)+''; document.getElementById('tP').innerHTML=eval(oT); setTimeout('dT()',1000); }
function aP(x){ return (x>11)?'pm':'am'; }
var dN=new Array('Sun','Mon','Tue','Wed','Thu','Fri','Sat'),mN=new Array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'),oT="dN[tS().getDay()]+' '+tS().getDate()+dE(tS().getDate())+' '+mN[tS().getMonth()]+' '+y2(tS().getYear())+' '+':'+':'+' '+tH(tS().getHours())+':'+lZ(tS().getMinutes())+':'+lZ(tS().getSeconds())+aP(tS().getHours())";
if(!document.all){ window.onload=dT; }else{ dT(); }
</script>
<!-- Clock Part 2 - Ends Here -->
<script type="text/javascript">
//###################################################################
// Author: ricocheting.com
// Version: v3.0
// Date: 2014-09-05
// Description: displays the amount of time until the "dateFuture" entered below.
var CDown = function() {
this.state=0;// if initialized
this.counts=[];// array holding countdown date objects and id to print to {d:new Date(2013,11,18,18,54,36), id:"countbox1"}
this.interval=null;// setInterval object
}
CDown.prototype = {
init: function(){
this.state=1;
var self=this;
this.interval=window.setInterval(function(){self.tick();}, 1000);
},
add: function(date,id){
this.counts.push({d:date,id:id});
this.tick();
if(this.state==0) this.init();
},
expire: function(idxs){
for(var x in idxs) {
this.display(this.counts[idxs[x]], "Sorry, hopfully we are open in a couple minutes");
this.counts.splice(idxs[x], 1);
}
},
format: function(r){
var out="";
if(r.d != 0){out += r.d +" "+((r.d==1)?"Day":"Days")+", ";}
if(r.h != 0){out += r.h +" "+((r.h==1)?"Hour":"Hours")+", ";}
out += r.m +" "+((r.m==1)?"Min":"Mins")+", ";
out += r.s +" "+((r.s==1)?"Sec":"Secs")+", ";
return out.substr(0,out.length-2);
},
math: function(work){
var y=w=d=h=m=s=ms=0;
ms=(""+((work%1000)+1000)).substr(1,3);
work=Math.floor(work/1000);//kill the "milliseconds" so just secs
y=Math.floor(work/31536000);//years (no leapyear support)
w=Math.floor(work/604800);//weeks
d=Math.floor(work/86400);//days
work=work%86400;
h=Math.floor(work/3600);//hours
work=work%3600;
m=Math.floor(work/60);//minutes
work=work%60;
s=Math.floor(work);//seconds
return {y:y,w:w,d:d,h:h,m:m,s:s,ms:ms};
},
tick: function(){
var now=(new Date()).getTime(),
expired=[],cnt=0,amount=0;
if(this.counts)
for(var idx=0,n=this.counts.length; idx<n; ++idx){
cnt=this.counts[idx];
amount=cnt.d.getTime()-now;//calc milliseconds between dates
// if time is already past
if(amount<0){
expired.push(idx);
}
// date is still good
else{
this.display(cnt, this.format(this.math(amount)));
}
}
// deal with any expired
if(expired.length>0) this.expire(expired);
// if no active counts, stop updating
if(this.counts.length==0) window.clearTimeout(this.interval);
},
display: function(cnt,msg){
document.getElementById(cnt.id).innerHTML=msg;
}
};
window.onload=function(){
var cdown = new CDown();
//Year,Month,Day,Hour,Min,Sec\\ (Jan - 0 Fed - 1 ++ Dec - 11, 12 is replaced with 0 for Jan)
cdown.add(new Date(2014,9,29,12,18,0), "countbox1");
};
</script>
<h2> Time until ^^<<>> opens!</h2>
<div id="countbox1"></div>
Fixed the problem
Thanks to #Scronide , #James Thorpe , and #Ultimater. I put all of your methods into place and kept them separate and used #Scronide final method. Thanks again.

They're both assigning to window.onload so the second is overwriting the function of the first.
If you are using jquery, instead of assigning to window.onload, you can instead use:
/* first component */
//initialisation for first component
$(function() {
dT();
});
/* second component */
//initialisation for second component
$(function() {
var cdown = new CDown();
//Year,Month,Day,Hour,Min,Sec\\ (Jan - 0 Fed - 1 ++ Dec - 11, 12 is replaced with 0 for Jan)
cdown.add(new Date(2014,9,29,12,18,0), "countbox1");
});

Both use window.onload. Simply join the two functions into one.

Neither of these scripts use any jQuery, so it isn't a jQuery conflict. The problem is that they are both setting a function to window.onload, so the last script will always override the one before it.
I suggest removing the if(!document.all){ window.onload=dT; }else{ dT(); } line from the end of the clock script and adding dT(); inside the window.onload assignment from the second script.
So you would have something like:
window.onload=function(){
dT();
var cdown = new CDown();
cdown.add(new Date(2014,9,29,12,18,0), "countbox1");
};

Related

Check is class exist longer than X in javascript

I wrote simple monitor which check few things on my networks and display status - I am fetching statuses using ajax.
When something is wrong I am adding class error to div which is displaying current status.
Later I add player with error sound when class error is present it plays music. I set 3 second interval and thats all.
But not always error mean error, sometimes I recive false warning.
Now I am looking for way to play sound when class error exists longer than XX seconds.
I suppose I have to wrote function with interval 1s, add every hit 1 to temp variable and check is variable bigger than else clean temp variable, but maybe is there more elegant way.
i guess it should work
$('.error').each(function(){
var e = $(this)
setTimeout(function(){
if (e.attr('class') == 'error'){
e.attr('class','error-with-sound');
}
},2000);
});
You should take two vars store the current time at their respective events.
var oldTime, newTime;
// Now when you are adding the class
$(something).addClass("someclass");
oldTime = new Date().getTime(); // Store the timestamp.
//And when you are removing the class
$(something).removeClass("someclass");
newTime = new Date().getTime(); // Store the timestamp.
// Now you check whether class was added for more then XX Seconds
var _diff = (newTime - oldTime)/1000; // Diference is in seconds.
There is no direct way for that, you can add timestamps in your class with separator something like error_1448953716457 and later you can split that and can compare with current timestamps
$('#na').click(function () {
var t = new Date().getTime();
$('h1').addClass("error_" + t);
});
$('#nr').click(function () {
var t = new Date().getTime();
$("[class^=error]").each(function (e) {
$("span").html("Diff. Seconds : " + ((t - ($(this).attr('class').split(' ').pop().split('_')[1])) / 1000).toString());
});
});
input {
width:100px;
}
.error {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<h1>.addClass()</h1>
<input id="na" value="Add Class1" type="button" />
<br/>
<input id="nr" value="Calculate Diff" type="button" />
<span></span>
If you want to track .error elements on the page, set an independent interval that looks for those elements and tracks the ones it has seen before by setting an attribute or data value in jquery.
Remember to clearInterval(interval) if you no longer need to check for .error elements.
(function ($) {
// set constants in milliseconds as desired
var INTERVAL_LENGTH = 100, // how often to check DOM for error elements
NOTIFY_AFTER = 3000; // handle error after this length
// check for .error elements and handle those that have been around for a while
var interval = setInterval(function () {
var now = Date.now();
$(".error").each(function () {
var t = $(this).data('error-time');
if(t) {
if(now - t > NOTIFY_AFTER) {
handleErrorElement(this);
}
}
else {
$(this).data('error-time', now);
}
});
}, INTERVAL_LENGTH);
function handleErrorElement(elem) {
// do what you need for error elements visible past a threshold
console.log("handling error element: ", elem);
}
})(jQuery);

setTimeout function not working

This is a basic timer from 01:00 to 00:00 and when it gets to 00:00 I want to show an alert that Time is up.
JsFiddle
To run faster I choose the second 58.
In firebug I see that jocsecunda1 and jocsecunda2 have these values, but I don't know why setTimeount is not triggered. Maybe I am putting it in the wrong place?
Thanks!
//just create html, ignore:
var pentruminut = document.createElement('span');
document.body.appendChild(pentruminut);
pentruminut.setAttribute('id','unminut');
document.getElementById('unminut').innerHTML="01:00";
window.onload=function(){
(function(){
setInterval(function(){
cro();
document.getElementById('unminut').innerHTML="0"+jocminut+":"+jocsecunda1+jocsecunda2;
},1000);
}());
}
var jocminut = 1;
var jocsecunda1 = 6;
var jocsecunda2 = 10;
function cro(){
if(jocsecunda1!=0||jocsecunda2!=0){
jocsecunda2 -=1;
while(jocminut==1){
jocminut-=1;
jocsecunda1 -=1;
}
while(jocsecunda2==-1){
jocsecunda1-=1;
jocsecunda2=9;
}
}
}
//here is the issue:
(function(){setTimeout(function(){
if (jocsecunda1==5&&jocsecunda2==8){
alert("Time is up");
}
},1000);}())
Your setTimeout is set to run only once, with a 1000 millisecond timeout, so the check for 58 seconds is made only once when the timer is at 59 seconds.
A better solution would be to change the way your program works, and instead check when your variables jocsecunda1 == 5 and jocsecunda2 == 8, and fire the alert then.
Example fildde: http://jsfiddle.net/L7u26/4/

setTimeout executes itself right away/on clear

I'm making a webpage where user events are logged in.
To test the feature I made a small, independant webpage with a teaxtarea and a text input. The events logged are those performed on the input element.
I want to prevent the same event text to be shown multiple times in a row, but I can't seem to prevent them from showing up!
I also want to add a line to separate event groups 0.5 seconds after no other event happened, but the line seems to appear on every event trigger, evenif I use clearTimeout with the timeout ID.
Basically: I don't want any line to be repeated. If the last line is a separator line, then it must not add another one. Yet it doesn't see to work.
JSFiddle Demo
Here is my code:
JavaScript
var timerID = 0;
function addSeparateLine()
{
document.getElementById('listeEvenements').value += "--------------------\n";
}
function show(newEventText)
{
var eventListField = document.getElementById('listeEvenements');
var eventList = [];
if (eventListField.value.length > 0)
{
eventList = eventListField.value.split("\n");
}
var eventCounter = eventList.length;
if (eventList[eventCounter - 2] == newEventText)
{
clearTimeout(timerID);
newEventText = "";
}
timerID = setTimeout(addSeparateLine, 500);
if (newEventText !== "")
{
eventListField.value += newEventText + "\n";
}
return true;
}
HTML
<fieldset id="conteneurLogEvenements">
<legend>Events called from HTML attribute</legend>
<textarea id="listeEvenements" rows="25"></textarea>
<input id="controleEcoute" type="text" onBlur="show('Blur');" onchange="show('Change');" onclick="show('Click');" onfocus="show('Focus');" onMousedown="show('MouseDown');" onMousemove="show('MouseMove');" onMouseover="show('MouseOver');" onkeydown="show('KeyDown');"
onkeypress="show('KeyPress');" onkeyup="show('KeyUp');" />
</fieldset>
http://jsfiddle.net/z6kb4/2/
It sounds like what you want is a line that prints after 500 milliseconds of inactivity, but what your code currently says to do is "print a line 500 milliseconds after any action, unless it gets canceled". You can get better results by structuring the code more closely to your intended goal.
Specifically, instead of scheduling a new timeout every time an event occurs, simply start a loop when the first event occurs that checks the time that has elapsed since the most recent event received and then prints a line when the elapsed time exceeds the desired threshold (500 milliseconds). Something like:
function addSeparateLine() {
var elapsed = new Date().getTime() - lastEventTime;
if (elapsed >= 500) {
document.getElementById('listeEvenements').value += "--------------------\n";
clearInterval(timerID);
timerID = -1;
}
}
...and then you schedule it like:
if(newEventText !== "") {
lastEventTime = new Date().getTime();
eventListField.value += newEventText+"\n";
if (timerID == -1) {
timerID = setInterval(addSeparateLine,100);
}
}
Working example here: http://jsfiddle.net/z6kb4/4/
Because you are not actually stopping the show function in any way. The clearTimeout only applies to the separator add. I have updated your fiddle. You need to wrap your function with
if (+new Date() - lastfire < 500) return;
and
lastfire = +new Date();
(before the last return--see the updated fiddle). Also, make sure to stick the global definition var lastfire = -1; somewhere up top.

lightweight jQuery countdown

I've seen some really nice looking jQuery plugins to count down the number of day, hours, minutes and seconds. They use images and look great.
But I'm looking for a simple little countdown that populates a div with the number of seconds remaining.
I'm going to use it in conjunction with:
function submitform() {
document.forms[0].submit();
}
jQuery(function($) {
setInterval("submitform()",20000);
});
I just want something real unobtrusive in the corner somewhere to let them know that the page is about to refresh all by itself.
First off, setInterval is used when you want to fire a function at set intervals, for example once every twenty seconds. For one-off events use setTimeout.
Here is a lightweight solution for you, assuming you have a div with an id of countdown:
$(function() {
var seconds = 20;
setTimeout(updateCountdown, 1000);
function updateCountdown() {
seconds--;
if (seconds > 0) {
$("#countdown").text("You have " + seconds + " seconds remaining");
setTimeout(updateCountdown, 1000);
} else {
submitForm();
}
}
});
function submitForm() {
document.forms[0].submit();
}
I just wrote a countdown for a project this week. It's just javascript, no jQuery needed.
Just pass the id of the div you want to place the countDown in, and the end and start time in milliseconds (or you can change how the Date params work, I had the dates in ms on the page already, so I passed them into the function, but you could do it differently):
<div id="countDownDiv"></div>
<script type="text/javascript">
countDown("countDownDiv",1281239850163, new Date().getTime());
</script>
And here's the function:
function countDown(id, end, cur){
this.container = document.getElementById(id);
this.endDate = new Date(end);
this.curDate = new Date(cur);
var context = this;
var formatResults = function(day, hour, minute, second){
var displayString = [
'<div class="stat statBig"><h3>',day,'</h3><p>days</p></div>',
'<div class="stat statBig"><h3>',hour,'</h3><p>hours</p></div>',
'<div class="stat statBig"><h3>',minute,'</h3><p>minutes</p></div>',
'<div class="stat statBig"><h3>',second,'</h3><p>seconds</p></div>'
];
return displayString.join("");
}
var update = function(){
context.curDate.setSeconds(context.curDate.getSeconds()+1);
var timediff = (context.endDate-context.curDate)/1000;
// Check if timer expired:
if (timediff<0){
return context.container.innerHTML = formatResults(0,0,0,0);
}
var oneMinute=60; //minute unit in seconds
var oneHour=60*60; //hour unit in seconds
var oneDay=60*60*24; //day unit in seconds
var dayfield=Math.floor(timediff/oneDay);
var hourfield=Math.floor((timediff-dayfield*oneDay)/oneHour);
var minutefield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour)/oneMinute);
var secondfield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour-minutefield*oneMinute));
context.container.innerHTML = formatResults(dayfield, hourfield, minutefield, secondfield);
// Call recursively
setTimeout(update, 1000);
};
// Call the recursive loop
update();
}

Strange problem with JavaScript code

Hi Masters Of Web Development,
first I want to say that I did not believe in my eyes - I've got a piece of javascript that works just fine in IE7, and don't in Firefox!!! :)))) That was little joke. :)
So I already told you the problem (it wasn't joke), now I'm pasting the javascript:
<script type="text/javascript">
<!-- This script and many more are available free online at -->
<!-- The JavaScript Source!! http://javascript.internet.com -->
<!-- Begin
var ms;
ms = %%CONTENT_REFRESH%% - 5;
var stop;
stop = 0;
var myvalue;
function display() {
if (!stop) {
setTimeout("display();", 1000);
}
thetime.value = myvalue;
}
function recalc() {
var hours;
var minutes;
var seconds;
ms = ms - 1;
hours = Math.floor(ms / 3600);
minutes = Math.floor(ms / 60);
if (minutes < 10) {
minutes = "0"+minutes;
}
seconds = ms - (minutes*60) - (hours*3600);
if (seconds < 10) {
seconds = "0"+seconds;
}
myvalue = hours+":"+minutes+":"+seconds;
thetime.value = myvalue;
if (myvalue == "0:00:00") {
stop = 1;
}
if (!stop) {
setTimeout("recalc();", 1000);
}
}
// End -->
</SCRIPT>
This is very old script I know that. It takes my current remaining song time, from my winamp and countdowns in site. But as I said, it does not work in Firefox.
Body and code that calls countdown timer looks like this:
<body class="playlist_body" onLoad="recalc();display();">
Time Left In Song: <INPUT align="center" TYPE="text" Name="thetime" size=5 />
</body>
//Edit: I look at FireBug, and I saw the following error:
thetime is not defined
recalc()playlist.cgi (line 87)
function onload(event) { recalc(); display(); }(load )1 (line 2)
error source line: [Break on this error] thetime.value = myvalue;\n
The problem is that it's accessing DOM elements by name.
Add the following code to the top to declare a variable for the thetime element, add id="thetime" to the INPUT, and add a call to init(); in onload in the body element.
var thetime;
function init() {
thetime = document.getElementById('thetime');
}
By the way, you can replace the textbox with a regular DIV element by setting the div's ID to thetime, and replacing thetime.value with thetime.innerHTML.
Also, it's better to call setTimeout with a function instead of a string; you should replace "display();" and "recalc();" with display and recalc respectively.
IE has a "feature" where an element with a name attribute is placed in the window object, eg.
<div name=foo></div>
Will give you a variable "foo" -- this is non-standard, you should do
document.getElementByName("foo")
To get the timer output element.
var thetime = document.getElementById("thetime");
and add id="thetime" instead of just name="thetime" to the input

Categories