Fadein at certain hour or time - javascript

I wonder if this is possible? For a website concept I want to make something pop out or fade in at a certain hour according to the user's computer time. I have tried looking with no avail because I don't know what kind of function would control when an effect takes place.
Any ideas? Thank you.

If you know at what time to fadeIn (ahem) in, then simply calculate the delta between that time (that's supposedly in the future) and our time. Example:
var dateNow = new Date();
setTimeout(function() {
doFadingInStuff();
}, dateWanted - dateNow);

If you get the current time and calculate the future time that you want the event to happen (thus you have an amount of elapsed time until your event should happen), you can use the setTimeout() function to schedule a function call at a precise time in the future. From that function, you would do your animation.

Check out this fiddle
Your JS
var now = new Date().toString();
$('#fadeMe').html(now).fadeIn(9000)

Assuming you only want something to be visible during a certain hour (ie. fade in when it becomes that hour, fade out when it's no longer that hour), you could do this:
// element is assumed to be a jQuery object
var VISIBLE_HOUR=14; // 2:00 PM
function check() {
var isHour=(new Date()).getUTCHours()==VISIBLE_HOUR;
var isVisible=element.is(":visible");
if(isHour!=isVisible) {
element.fadeToggle(1000);
}
}
// We probably don't want to check very frequently...
// You could make it more advanced by checking
// more frequently closer to the hour in which it would be visible.
setInterval(check, 30000);

var eventHour = 16, // 4:00pm
// get the current time as a Date
now = new Date(),
// turn your event time into a Date
eventDate = new Date(now.getFullYear(),
now.getMonth(),
now.getDate(),
eventHour),
// calculate how many MS until your event
eventTimeMS = eventDate - now;
dayInMS = 86400000,
// your event
myEvent = function() {
alert('The time is now!');
};
// adding 24 hours if already past event time today
eventTimeMS = eventTimeMS < 0 ? eventTimeMS + dayInMS : eventTimeMS;
// if currently the right hour, just invoke event
if (eventHour == now.getHours()) {
myEvent();
// otherwise start a timer to invoke your event at the appropriate time
} else {
setTimeout(myEvent, eventTimeMS);
}

I think you want to check the time of day for the client, then fade in or out. This would be done like so:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function(){
var sunriseHour = 1;
var sunsetHour = 19;
function checkForChange() {
var nowDate = new Date();
var nowHour = nowDate.getHours();
if ((nowHour >= sunriseHour) && (nowHour < sunsetHour)) {
if (sunPosition != 'up') {
sunPosition = 'up';
$('#theSun').fadeIn('slow');
}
} else {
if (sunPosition != 'down') {
sunPosition = 'down';
$('#theSun').fadeOut('slow');
}
}
}
var nowDate = new Date();
var nowHour = nowDate.getHours();
if ((nowHour >= sunriseHour) && (nowHour < sunsetHour)) {
$('#theSun').show();
sunPosition = 'up';
} else {
$('#theSun').hide();
sunPosition = 'down';
}
setTimeout(checkForChange, 1000);
});
</script>
</head>
<body>
<div id="theSun" style="background: yellow; width: 300px; height: 300px; display: none;">
This box is the sun
</div>
</body>
</html>

Related

How to add audio to a 10 second countdown in javascript

First time posting on here so go easy.
I am having some problems with a recent project. I am trying to create a countdown as the landing page with audio sounds for each number (street fighter 2 sound effects if anyone is familiar). I have managed to get the countdown to work and it will work but only at the click of a button as this is the only way I could get it to work.
Like I said this is not the desired effect as once the countdown finishes I want it to load the main page. Also in regards to adding the sound to each individual number, I have absolutely no idea where to start!
This is my current JS for it
document.addEventListener('DOMContentLoaded', () => {
const timeLeftDisplay = document.querySelector('#time-left')
const startBtn = document.querySelector('#start-button')
let timeLeft = 10
function countDown (){
setInterval(function(){
if(timeLeft <= 0){
clearInterval(timeLeft = 0)
}
timeLeftDisplay.innerHTML = timeLeft
timeLeft -= 1
}, 1000)
}
startBtn.addEventListener('click', countDown)
} )
This is the current HTML
<script type= "text/javascript" src="assets/javascript/script.js"></script>
<title>Bro-nament</title>
</head>
<body>
<div class="container text-center">
<h1 class="bro-title"> TIME TILL BRO - DOWN</h1>
<h2 id="time-left"> 10 </h2>
<button id="start-button"> <i class="fas fa-fist-raised"> Continue? </i> <i class="fas fa-fist-raised"></i></button>
Current page view
Thanks
In your server, you need to name your audio files with a number for all of them and use the value of time variable to increment and get the url of the file for each every seconde.
Like :
9.mp3
8.mp3
7.mp3
6.mp3
....
Once the counter is to 0, you redirect where the url you want.
let time = 10;
countdown();
function countdown() {
// we upadate number text
document.querySelector('#time-left').textContent = --time;
// if count is equal to 0 (end of counter)
if (time === 0) {
time = 10;
// we redirect to this url
window.location.href = "http://www.google.com";
// we stop the loop
return false;
}
//console.log(time);
// we set the url of audio file for each seconde
const audio = new Audio("https://srv-store5.gofile.io/download/RFgvcw/" + time + ".mp3");
// if you only want one, u dont need the const time
//const audio = new Audio("https://srv-store5.gofile.io/download/RFgvcw/1.mp3");
audio.play();
setTimeout(countdown, 1000);
}
#time-left {
font-size: 150px;
font-weight: bold;
margin: auto 0;
text-align: center;
}
<div id="time-left"></div>

need javascript to automatically reload page when minute updates

I am using the following code in my website which displays the current time
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('time').innerHTML =
h + ":" + m;
var t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
i am also using the automatic refresher tag in my html which reloads page after every 60 seconds
<meta http-equiv="refresh" content="60">
what i want is whenever the time changes to next minute the page reloads
which means if current time is 14:05 and when it hits 14:06 the page reloads by reading this time change and NOT by 60 seconds interval from which the user opens the page.
You can set timeout looking at the clock, just get the actual seconds and wait til 60 to reload:
var date = new Date();
setTimeout(function(){
window.location.reload(1);
},(60 - date.getSeconds())*1000)
Just put that at the head inside a script tag
Try using this
setTimeout(function(){
window.location.reload(1);
}, 60000); // 60 sec
Source: How to reload page every 5 second?
or take a look at this too
setTimeout(function(){
var minutes = (new Date()).getMinutes()
if ( !minutes%15 ) location.reload(); // if minutes is a multiple of 15
},60000); // 60.000 milliseconds = 1 minute
Source: jQuery auto refresh page on clock time
Handling the local time using client side script is not recommended because the user's clock might be messed up and thus your system would turn out to be faulty.
So it is better you fetch time from your server using any server-side language like PHP
In PHP:
<?php
echo date("h:i");
?>
Now you can call this function using AJAX and you can easily handle your time.
var result=null;
function getDate(){
var result=$.ajax({
url: "script.php",
type: "POST",
success: function(data){
setTimeOut(function(){getDate();},60000);
}
}).responseText;
}

Get the time show animation how much duration is currntly running

In jquery i use following code:
j=-(i)
if(j%2==1)
{
$("#caption1").hide();
$("#caption1").fadeIn(1000);
$('#main_div').hide();
$('#main_div').show(5000);
}
}
if(i%2==0)
{
$("#caption1").hide();
$("#caption1").fadeIn(1000);
$('#main_div').hide();
$('#main_div').show(5000);
}
while show animation i want the duration of animation completed?
for Example:
i set it show animation for 5secs.
show animation now started.
2 secs animation completed[ 3secs remaining]
in this case i need this completed duration[2secs] on button click??
Mark down the time when the animation started:
var animationStarted = new Date();
$('#main_div').show(5000);
....
When you need to show how much time has passed, take the current time and subtract the time saved in the previous step.
var now = new Date();
var elapsed = ( now.getTime() - animationStarted.getTime() ) / 1000;
Demo: http://jsfiddle.net/NZGU6/

JQuery progress bar pauses when browser tab is changed

I'm trying to display a progress bar on a html page using javascript. However,
when the browser tab containing the code becomes inactive, the progress bar stops updating,
being resumed when the tab is active again.
How can I prevent the browser from stopping/pausing the execution of javascript code when the window is inactive?
Although it may be irrelevant, here is the code:
Object.progressBar = function(){
$( "#question-progress-bar" ).progressbar({
value: false,
complete: function(event, ui) { ... }
});
var seconds = 15.0,
progressbar = $("#question-progress-bar"),
progressbarValue = progressbar.find(".ui-progressbar-value");
progressbarValue.css({
"background": '#c5b100',
"opacity" : '0.8'
})
var int = setInterval(function() {
var percent = (15-seconds)/15*100;
seconds=seconds-0.1;
progressbar.progressbar( "option", {
value: Math.ceil(percent)
});
$("#question-progress-bar-seconds").html((seconds).toFixed(1)+"s");
if (seconds <= 0.1) {
clearInterval(int);
}
}, 100);
}
Instead of using setInterval and assuming a certain amount of time has passed between calls (even when it's up front, setInterval has hit or miss accuracy) use the Date object to get a time when the bar starts, and compare that to the current time at each iteration.
<html>
<head>
<script>
function go()
{
var pb = new ProgressBar(5, "targ");
}
window.onload = go;
function ProgressBar(l, t)
{
var start = Date.now();
var length = l * 1000;
var targ = document.getElementById(t);
var it = window.setInterval(interval, 10);
function interval()
{
var p = 100 * (Date.now() - start) / length;
if(p > 100)
{
p = 100;
window.clearInterval(it);
alert("DONE"); // alternatively send an AJAX request here to alert the server
}
targ.value = (Math.round(p) + "%");
}
}
</script>
</head>
<body>
<input type="text" id="targ" />
</body>
</html>
I've made an example object, here, that immediately starts a countdown when instantiated and calls an alert and kills the interval timer when done. Alternatively an AJAX call, or any other sort of call can be done upon completion.
It should be noted that this will NOT complete the call if the browser stops Javascript all together. It will, however, complete it as soon as the tab has been given focus again if enough time has passed in the interim. There is no way for a website to alter this sort of browser behavior from the scripting side.
Hope that helps!

Fast forward timer

I'm having trouble with fast forwarding a timer. It is very basic at this stadium. I have a interval that add numbers. Like this:
setInterval(function () {
//+1 second
//Format output to 00:00
//Handle minute update
}, 1000);
This works perfect. The timer is going at normal speed. What I want to do is fast forwarding this timer. I want a timer minute to take 1 real second. I have tried:
setInterval(function () {
//+1 second
//Format output to 00:00
//Handle minute update
}, 15);
That works sometimes and sometimes not. Sometimes it stops att 01:02 instead of 01:00. It may be my lack of math knowledge but I don't know. How would you do it? I am going to stop and start the timer every "timer minute" so it's important that the interval is correct.
EDIT
Here is a fiddle of how I want it to work: http://jsfiddle.net/tbleckert/pF4gs/
EDIT 2
Maybe I should just adjust the time when I stop the timer?
EDIT 3
It seems like 15 ms works most of the times. But something makes ut unreliable, I think the best way is to just adjust the time.
I think what you should be doing is storing your interval in a variable so that you can clear it, and start it again with a different delay.
var delay = 1000; // JavaScript uses milliseconds, so 1000 = 1 second
var theTimer = '';
function startTimer(){
theTimer = setInterval(function () {
// Do awesome stuff here
}, delay);
}
startTimer();
Now when you want to change the interval, or fast forward the timer, all you have to do is clear the current setInterval and define it again -
clearInterval(theTimer); // stop and clear the current timer
delay = 500; // Crank it up to twice the speed! 0.5 seconds!
startTimer(); // start a new setInterval();
Here is a simple demo
<!DOCTYPE html>
<html>
<head>
<script>
function myTimer(){
this.startTime=0;
this.intervalID=0;
this.timePassed=0;
this.multiplier=1;
this.outputElement=null;
this.start=function(){
clearInterval(this.intervalID);
this.timePassed=0;
this.outputElement=document.getElementById("output");
this.startTime=new Date();
var me = this;
this.intervalID=setInterval(function(){
me.update(me);
},100);
}
this.toTwoDigit=function(num){
if(num<10){
return "0"+num;
}
return new String(num);
}
this.toThreeDigit=function(num){
if(num<10){
return "00"+num;
}
if(num<100){
return "0"+num;
}
return new String(num);
}
this.update=function(me){
me.timePassed=me.timePassed+(100*me.multiplier);
var seconds=Math.floor(me.timePassed/1000);
var hours = Math.floor(seconds/3600);
var minutes = seconds-(hours*3600);
seconds = seconds%60;
minutes=Math.floor(minutes/60);
me.outputElement.innerHTML= me.toTwoDigit(hours)+":"
+me.toTwoDigit(minutes)+":"
+me.toTwoDigit(seconds)
+":"+me.toThreeDigit(Math.floor(me.timePassed%1000));
}
this.speedup=function(){
this.multiplier=this.multiplier*2;
}
this.slowDown=function(){
this.multiplier=this.multiplier/2;
}
this.stop=function(){
clearInterval(this.intervalID);
this.update(this);
}
}
var t = new myTimer();
</script>
</head>
<body onload="t.start();">
<input type="button" value="speed up" onclick="t.speedup()"></input>
<input type="button" value="slow down" onclick="t.slowDown()"></input>
<input type="button" value="stop" onclick="t.stop()"></input>
<input type="button" value="restart" onclick="t.start()"></input>
<input type="button" value="(re)start times 60" onclick="t.multiplier=60;t.start()"></input>
<div id="output"></div>
</body>
</html>
Ok so I'm going to answer this myself. I don't think I was clear enough. When I start the timer a timeout starts at the same time, that after one second stops the timer. This is where it goes wrong, the timer doesn't always show 01:00 when it stops.
So, the final solution is the set the seconds to 00 every time it stops, and because it all happens so fast, you wont notice.
setTimeout(function () {
clearInterval(interval);
$('.clock').html(rMin.slice(-2) + ':00');
}, 1000);
Check my updated fiddle:
http://jsfiddle.net/tbleckert/pF4gs/2/

Categories

Resources