I found a good custom HTML5 audio player and successfully redesigned it for my needs. Everything about it is ok, except it didn't show "remaining" time (how much time actually left to track end).
I want to add a calculation of time left without changing the original script, Is it possible?
[
function calculateTotalValue(length) {
var minutes = Math.floor(length / 60),
seconds_int = length - minutes * 60,
seconds_str = seconds_int.toString(),
seconds = seconds_str.substr(0, 2),
time = minutes + ':' + seconds
return time;
}
function calculateCurrentValue(currentTime) {
var current_hour = parseInt(currentTime / 3600) % 24,
current_minute = parseInt(currentTime / 60) % 60,
current_seconds_long = currentTime % 60,
current_seconds = current_seconds_long.toFixed(),
current_time = (current_minute < 10 ? "0" + current_minute : current_minute) + ":" + (current_seconds < 10 ? "0" + current_seconds : current_seconds);
return current_time;
}
CodePen (original player source code)
What you want is extremely easy, You don't have to change a lot of code but just need to add just two lines.
Inside the "initProgressBar()" function just add these two lines of code
//calculate the remaining time
var rem_time=length-current_time;
jQuery(".rem-time").html(calculateCurrentValue(rem_time));
//HTML to show the remaining time(add it to the HTML)
<small style="float: left; position: relative; left: 15px;" class="rem-time"></small>
the first line is just getting the total seconds, "length" and "current_time" was already available in the code so I am just using them, nothing new.
In the second line, I am converting the remaining time to a readable format, again using an already available function "calculateCurrentValue()" and setting an HTML element with remaining time.
At last the HTML element in which the remaining time will be shown.
You can also take a look at this CodePen which I have done for a better understanding.
Adding Full code here to make sure it is available always
function calculateTotalValue(length) {
var minutes = Math.floor(length / 60),
seconds_int = length - minutes * 60,
seconds_str = seconds_int.toString(),
seconds = seconds_str.substr(0, 2),
time = minutes + ':' + seconds
return time;
}
function calculateCurrentValue(currentTime) {
var current_hour = parseInt(currentTime / 3600) % 24,
current_minute = parseInt(currentTime / 60) % 60,
current_seconds_long = currentTime % 60,
current_seconds = current_seconds_long.toFixed(),
current_time = (current_minute < 10 ? "0" + current_minute : current_minute) + ":" + (current_seconds < 10 ? "0" + current_seconds : current_seconds);
return current_time;
}
var prevcurrentime=0;
function initProgressBar() {
var player = document.getElementById('player');
var length = player.duration
var current_time = player.currentTime;
// calculate total length of value
var totalLength = calculateTotalValue(length)
jQuery(".end-time").html(totalLength);
// calculate current value time
var currentTime = calculateCurrentValue(current_time);
jQuery(".start-time").html(currentTime);
//checking if the current time is bigger than the previous or else there will be sync different between remaining and current
if(currentTime>prevcurrentime){
//calculate the remaining time
var rem_time=length-current_time;
jQuery(".rem-time").html(calculateCurrentValue(rem_time));
}
//setting the previouscurrent time to this current time
prevcurrentime=currentTime;
//progress bar calculation
var progressbar = document.getElementById('seekObj');
progressbar.value = (player.currentTime / player.duration);
progressbar.addEventListener("click", seek);
if (player.currentTime == player.duration) {
$('#play-btn').removeClass('pause');
}
function seek(evt) {
var percent = evt.offsetX / this.offsetWidth;
player.currentTime = percent * player.duration;
progressbar.value = percent / 100;
}
};
function initPlayers(num) {
// pass num in if there are multiple audio players e.g 'player' + i
for (var i = 0; i < num; i++) {
(function() {
// Variables
// ----------------------------------------------------------
// audio embed object
var playerContainer = document.getElementById('player-container'),
player = document.getElementById('player'),
isPlaying = false,
playBtn = document.getElementById('play-btn');
// Controls Listeners
// ----------------------------------------------------------
if (playBtn != null) {
playBtn.addEventListener('click', function() {
togglePlay()
});
}
// Controls & Sounds Methods
// ----------------------------------------------------------
function togglePlay() {
if (player.paused === false) {
player.pause();
isPlaying = false;
$('#play-btn').removeClass('pause');
} else {
player.play();
$('#play-btn').addClass('pause');
isPlaying = true;
}
}
}());
}
}
initPlayers(jQuery('#player-container').length);
html {
height: 100%;
display: table;
margin: auto;
}
body {
height: 100%;
display: table-cell;
vertical-align: middle;
background: yellow;
}
.audio-player {
background: white;
border: 1px solid #dfdfdf;
width: 50vw;
text-align: center;
display: flex;
flex-flow: row;
margin: 4rem 0 4rem 0;
}
.audio-player .album-image {
min-height: 100px;
width: 110px;
background-size: cover;
}
.audio-player .player-controls {
align-items: center;
justify-content: center;
margin-top: 2.5rem;
flex: 3;
}
.audio-player .player-controls progress {
width: 90%;
}
.audio-player .player-controls progress[value] {
-webkit-appearance: none;
appearance: none;
background-color: white;
color: blue;
height: 5px;
}
.audio-player .player-controls progress[value]::-webkit-progress-bar {
background-color: white;
border-radius: 2px;
border: 1px solid #dfdfdf;
color: blue;
}
.audio-player .player-controls progress::-webkit-progress-value {
background-color: blue;
}
.audio-player .player-controls p {
font-size: 1.6rem;
}
.audio-player #play-btn {
background-image: url("http://www.lukeduncan.me/images/play-button.png");
background-size: cover;
width: 75px;
height: 75px;
margin: 2rem 0 2rem 2rem;
}
.audio-player #play-btn.pause {
background-image: url("http://www.lukeduncan.me/images/pause-button.png");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="audio-player">
<div id="play-btn"></div>
<div class="audio-wrapper" id="player-container" href="javascript:;">
<audio id="player" ontimeupdate="initProgressBar()">
<source src="http://www.lukeduncan.me/oslo.mp3" type="audio/mp3">
</audio>
</div>
<div class="player-controls scrubber">
<p>Oslo <small>by</small> Holy Esque</p>
<span id="seekObjContainer">
<progress id="seekObj" value="0" max="1"></progress>
</span>
<br>
<small style="float: left; position: relative; left: 15px;" class="start-time"></small><br/>
<small style="float: left; position: relative; left: 15px;" class="rem-time"></small>
<small style="float: right; position: relative; right: 20px;" class="end-time"></small>
</div>
<div class="album-image" style="background-image: url('https://artwork-cdn.7static.com/static/img/sleeveart/00/051/614/0005161476_350.jpg')"></div>
</div>
Related
I am working on an application to help people create new habits or discard old ones. For this application, I want to have a countdown timer which counts down every day, thanks to this post I got this to work, the next step is to add a progress bar which counts down along with the timer (so basically 00:00 = full progress bar, 23:59 = empty progress bar).
I have been looking everywhere but I can't seem to figure it out or even get a start with it. I would like to see #goal-time decreasing.
I hope someone could give me some directions/hints or even some snippets if that's possible! Thanks!
(function() {
var start = new Date;
start.setHours(24, 0, 0); //hh:mm:ss
function pad(num) {
return ("0" + parseInt(num)).substr(-2);
}
function tick() {
var now = new Date;
if (now > start) { // too late, go to tomorrow
start.setDate(start.getDate() + 1);
}
var remain = ((start - now) / 1000);
var hh = pad((remain / 60 / 60) % 60);
var mm = pad((remain / 60) % 60);
var ss = pad(remain % 60);
document.getElementById('time').innerHTML = hh + ":" + mm + ":" + ss;
setTimeout(tick, 1000);
}
document.addEventListener('DOMContentLoaded', tick);
})();
.goal-progress {
border-color: black;
border-style: solid;
border-width: thick;
height: 80px;
margin-top: 50px;
margin-left: 20px;
margin-right: 20px;
background-color: black;
}
#time {
float: right;
line-height: 80px;
margin-right: 20px;
background-color: black;
color: white;
mix-blend-mode: difference;
}
.goal-time-container {
height: 80px;
background-color: white;
margin-left: 115px;
}
#goal-time {
background-color: black;
height: 80px;
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="goal-progress">
<div id="time"></div>
<!-- time countdown -->
<div id="img"></div>
<div class="goal-time-container">
<!-- container of the progress bar -->
<div id="goal-time"></div>
<!-- soon to (hopefully) be progress bar -->
</div>
</div>
To achieve this you can take the seconds held in the remain variable and use them to work out the percentage of the seconds remaining in one day, 86400, and then set that percentage as the width of the progress bar:
(function() {
var start = new Date;
start.setHours(24, 0, 0); //hh:mm:ss
function pad(num) {
return ("0" + parseInt(num)).substr(-2);
}
function tick() {
var now = new Date;
if (now > start) { // too late, go to tomorrow
start.setDate(start.getDate() + 1);
}
var remain = ((start - now) / 1000);
var hh = pad((remain / 60 / 60) % 60);
var mm = pad((remain / 60) % 60);
var ss = pad(remain % 60);
document.getElementById('time').innerHTML = hh + ":" + mm + ":" + ss;
// bar width calulation:
var pc = remain * (100 / 86400);
document.querySelector('#goal-time').style.width = pc + '%';
setTimeout(tick, 1000);
}
document.addEventListener('DOMContentLoaded', tick);
})();
.goal-progress {
border: 5px solid #000;
height: 80px;
margin: 50px 20px 20px 0;
background-color: black;
}
#time {
float: right;
line-height: 80px;
margin-right: 20px;
background-color: black;
color: white;
mix-blend-mode: difference;
}
.goal-time-container {
height: 80px;
background-color: white;
margin-left: 115px;
}
#goal-time {
background-color: black;
height: 80px;
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="goal-progress">
<div id="time"></div>
<div id="img"></div>
<div class="goal-time-container">
<div id="goal-time"></div>
</div>
</div>
You can user getTime() function to get the number of milliseconds difference b/w two dates.
eg
let diff = new Date("<future_date>").getTime() - new Date().getTime();
You can use diff value to set the progressbar style (width or percentage or whatever).
Another solution would be to add:
const totalSeconds = 24 * 60 * 60;
right after:
start.setHours(24,0,0)
Then add:
document.getElementById('goal-time').style.width = ((remain / totalSeconds) * 100) + '%';
right after:
document.getElementById('time').innerHTML = hh + ":" + mm + ":" + ss;
to calculate the width of your progress bar.
I've created a timer to count down to a specific date, it displays with no problem. But this time, I'd like to add vertical lines separating them. I attempted to borderLeft and height to see a vertical line, but had no luck. I do see the 1px solid border, though. The picture below illustrates what I want to see in the browser.
I also want the words (days, hours, minutes, seconds) to appear underneath the numbers. Based on the picture, it appears directly next to them. I attempted to use \n because I thought it would put the word in a new line, but that didn't work.
Do we even need use javascript achieve these things? What am I doing wrong and how can I fix it?
Here's my js:
var timerDisplay = document.getElementById("timer");
timerDisplay.innerHTML = days + "\ndays " + hours + "\nhours " + minutes + "\nminutes " + seconds + "\nseconds ";
timerDisplay.style.border = "1px solid";
timerDisplay.style.borderLeft = "6px solid"
timerDisplay.style.height = "10px";
Here's my html:
<p id="timer"></p>
You could add inline elements into the p, thus you could apply some styles to achieve your objective.
For example:
const timerDisplay = document.querySelector("#timer")
timerDisplay.appendChild(createSpan('126 days'))
timerDisplay.appendChild(createSpan('5 hours'))
timerDisplay.appendChild(createSpan('16 minutes'))
timerDisplay.appendChild(createSpan('33 seconds'))
function createSpan (text) {
const span = document.createElement('span')
span.textContent = text
return span
}
And with proper styles:
p {
border: solid 5px black;
background-color: teal;
}
span {
display: inline-block;
border-right: solid 5px black;
}
p span:first-child {
text-align: right;
width: 150px;
}
span:last-child {
border-right: none;
}
On the other hand, you could change your html code:
<p id="timer">
<span class="days">126 days</span>
<span class="hours"></span>
<span class="minutes"></span>
<span class="seconds"></span>
</p>
And then, you could change the span elements directly:
const timerDisplay = document.querySelector("#timer")
const days = timerDisplay.querySelector('.days')
const hours = timerDisplay.querySelector('.hours')
const minutes = timerDisplay.querySelector('.minutes')
const seconds = timerDisplay.querySelector('.seconds')
days.textContent = '126 days'
hours.textContent = '5 hours'
minutes.textContent = '16 minutes'
seconds.textContent = '33 seconds'
And with the same styles:
p {
border: solid 5px black;
background-color: teal;
}
span {
display: inline-block;
border-right: solid 5px black;
}
p span:first-child {
text-align: right;
width: 150px;
}
span:last-child {
border-right: none;
}
You can show the example in this jsfiddle: jsfiddle example
As Temani Afif mentioned in comments, you should devide each number to separate span and style them the way you like.
Here is a working example:
function countdown(endDate) {
let days, hours, minutes, seconds;
endDate = new Date(endDate).getTime();
if (isNaN(endDate)) {
return;
}
setInterval(calculate, 1000);
function calculate() {
let startDate = new Date();
startDate = startDate.getTime();
let timeRemaining = parseInt((endDate - startDate) / 1000);
if (timeRemaining >= 0) {
days = parseInt(timeRemaining / 86400);
timeRemaining = (timeRemaining % 86400);
hours = parseInt(timeRemaining / 3600);
timeRemaining = (timeRemaining % 3600);
minutes = parseInt(timeRemaining / 60);
timeRemaining = (timeRemaining % 60);
seconds = parseInt(timeRemaining);
document.getElementById("days").innerHTML = parseInt(days, 10)+' days';
document.getElementById("hours").innerHTML = ("0" + hours).slice(-2)+' hours';
document.getElementById("minutes").innerHTML = ("0" + minutes).slice(-2)+' minutes';
document.getElementById("seconds").innerHTML = ("0" + seconds).slice(-2)+' seconds';
} else {
return;
}
}
}
(function () {
countdown('04/01/2025 05:00:00 PM');
}());
.wrapper {
background: #0084FF;
border: #000 1px solid;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
span:not(:last-child) {
border-right: #000 1px solid;
}
span {
padding: 0 5px;
white-space: nowrap;
}
<div class="wrapper">
<span id="days"></span>
<span id="hours"></span>
<span id="minutes"></span>
<span id="seconds"></span>
</div>
I am building a timer that has a pause and resume function. I found out the user can set multiple intervals when the timer is clicked more than once.
How can I prevent users from setting multiple intervals?
I tried inserting ($('.clock)).off("click") once the interval has set, but then couldn't figure out how to resume it. I thought I could do a statement pause = true, but not sure how I can use it in my code.
let currentMins = 10
let currentCount = 10*60
let pause = true
$(document).ready(function(){
// --- SET TIME --- //
$('select').on('change', function(){
const timePair = {
pappardelle : 7,
penne : 10,
farfalle : 11,
bucatini : 8,
angelhair : 4,
gnocchi : 1,
orecchiette : 10,
justboiledeggs : 11
}
const selected = this.value
for(let keys in timePair){
let toPrint = ''
if(selected.split(' ').join('').toLowerCase() == keys){
toPrint = timePair[keys]
$('#mins').html(toPrint)
$('.clock').html(toPrint+':00')
currentMins = toPrint
currentCount = timePair[keys]*60
console.log('current counts on set: ',currentCount)
}
}
})
// --- UPDATE CLOCK --- //
//basic increment and decrement setting
$('.decrement').click(function(){
if((currentMins)>1){
currentMins-=1
currentCount-=60
$('#mins').html(currentMins)
$('.clock').html(currentMins + ':00')
console.log("current mins and count in decrement :", currentMins, currentCount)
}
})
$('.increment').click(function(){
if(currentMins<100){
currentMins+=1
currentCount += 60
$('#mins').html(currentMins)
$('.clock').html(currentMins + ':00')
console.log("current mins and count in increment :", currentMins, currentCount)
}
})
$('.clock').click(function(){
console.log("current currentCount in the starting clock div :", currentCount)
//interval setting
const interval = window.setInterval(function(){
if(currentCount == 0){
pause=true
$('.clock').html('Buon appetito!')
} else {
console.log("current currentCount in the else clause in clock div :", currentCount)
pause = false
currentCount --
let minuites = Math.floor(currentCount / 60)
let seconds = currentCount - minuites * 60
$('.clock').html(minuites + ':' + ('0' + seconds).slice(-2))
}
$('.pause').click(function(){
pause = true;
clearInterval(interval)
})
}, 1000)
$('select').on('change', function(){
pause = true;
clearInterval(interval)
})
})
})//end jquery
You can do that with a flag variable:
let started = false
and a conditional return statement:
if (started && !pause) {
return;
} else {
started = true;
}
All it does is when the clock is clicked, it checks to see if started is true. If it is, then the timer has already been enabled, so it just returns out of the function (unless it's paused). If the value of started is false, then the timer begins and the flag variable is set to true.
See this working example:
let currentMins = 10
let currentCount = 10 * 60
let pause = true
let started = false
$(document).ready(function() {
// --- SET TIME --- //
$('select').on('change', function() {
const timePair = {
pappardelle: 7,
penne: 10,
farfalle: 11,
bucatini: 8,
angelhair: 4,
gnocchi: 1,
orecchiette: 10,
justboiledeggs: 11
}
const selected = this.value
for (let keys in timePair) {
let toPrint = ''
if (selected.split(' ').join('').toLowerCase() == keys) {
toPrint = timePair[keys]
$('#mins').html(toPrint)
$('.clock').html(toPrint + ':00')
currentMins = toPrint
currentCount = timePair[keys] * 60
console.log('current counts on set: ', currentCount)
}
}
if (selected.indexOf('Seamless') != -1) {
window.open('http://seamless.com', '_blank')
}
})
// --- UPDATE CLOCK --- //
//basic increment and decrement setting
$('.decrement').click(function() {
if ((currentMins) > 1) {
currentMins -= 1
currentCount -= 60
$('#mins').html(currentMins)
$('.clock').html(currentMins + ':00')
console.log("current mins and count in decrement :", currentMins, currentCount)
}
})
$('.increment').click(function() {
if (currentMins < 100) {
currentMins += 1
currentCount += 60
$('#mins').html(currentMins)
$('.clock').html(currentMins + ':00')
console.log("current mins and count in increment :", currentMins, currentCount)
}
})
$('.clock').click(function() {
if (started && !pause) {
return;
} else {
started = true;
}
console.log("current currentCount in the starting clock div :", currentCount)
//interval setting
const interval = window.setInterval(function() {
if (currentCount == 0) {
pause = true
$('.clock').html('Buon appetito!')
} else {
console.log("current currentCount in the else clause in clock div :", currentCount)
pause = false
currentCount--
let minuites = Math.floor(currentCount / 60)
let seconds = currentCount - minuites * 60
$('.clock').html(minuites + ':' + ('0' + seconds).slice(-2))
}
$('.pause').click(function() {
pause = true;
clearInterval(interval)
})
}, 1000)
$('select').on('change', function() {
pause = true;
clearInterval(interval)
})
})
}) //end jquery
body {
margin: 50px;
font-family: 'Cormorant Garamond', serif;
color: tomato;
}
main {
justify-content: center;
}
h1 {
font-size: 40px;
text-align: center;
}
.grid {
display: grid;
grid-gap: 10px;
grid-template-columns: [col1-start] 130px [col2-start] 130px [col3-start] 140px [col3-end];
grid-template-rows: [row1-start] 120px [row2-start] 120px [row2-end];
background-color: #fff;
color: tomato;
justify-content: center;
}
.box {
color: tomato;
padding: 30px;
font-size: 150%;
border: 1px solid tomato;
}
.food {
grid-column: col1-start / col3-start;
grid-row: row1-start;
}
.clock {
grid-column: col3-start;
grid-row: row1-start / row2-end;
display: flex;
justify-content: center;
align-items: center;
}
.clock:hover {
color: #ffd700;
font-size: 25px;
cursor: pointer;
}
.settimer {
grid-column: col1-start;
grid-row: row2-start;
display: flex;
flex-direction: row;
flex-wrap: nowrap;
justify-content: center;
align-items: center;
align-content: stretch;
}
.settimer div {
margin: 5px;
}
#mins {
align-items: center;
font-size: 20px;
}
.icon {
font-size: 15px;
}
.icon:hover {
color: #ffd700;
cursor: pointer;
font-size: 18px;
}
.pause {
grid-column: col2-start;
grid-row: row2-start;
font-size: 20px;
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
align-content: stretch;
}
.pause:hover {
color: #ffd700;
cursor: pointer;
}
<!DOCTYPE html>
<html>
<head>
<script defer src="https://use.fontawesome.com/releases/v5.0.6/js/all.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="pomodoro.css" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css?family=Cormorant+Garamond:400,700" rel="stylesheet">
<script src="pomodorooo.js"></script>
<title>Pomodoro Clock</title>
</head>
<body>
<main>
<h1>Pomodoro clock</h1>
<div class="grid">
<div class="box food">Set the timer for
<select id="pasta">
<option id="0">I meant, pasta</option>
<option id="1">Pappardelle</option>
<option id="2">Penne</option>
<option id="3">Farfalle</option>
<option id="4">Bucatini</option>
<option id="5">Angel Hair</option>
<option id="6">Gnocchi</option>
<option id="7">Orecchiette</option>
<option id="8">Just boiled eggs</option>
<option id="9">Take me to Seamless already</option>
</select>
<!-- deleted form -->
</div>
<!-- a click box that has various food options, default set for each food -->
<div class="box clock">Start</div>
<!-- a blank circle. will be filled red-->
<div class="box settimer">
<div class="decrement icon"><i class="fas fa-caret-left"></i></div>
<div id="mins">Ready</div>
<!-- deleted span -->
<div class="increment icon"><i class="fas fa-caret-right"></i></div>
</div>
<!-- timer set. increment and decrement enabled -->
<div class="box pause">Pause</div>
<!-- break set. increment and decrement enabled -->
</div>
</main>
<br /><br /><br /><br /><br /><br />
</body>
</html>
Ok I have created a stamina container that has three stamina bars within each other, and when you click on the attack button some of the stamina is taken off the first stamina bar. However, if you keep clicking on the first stamina bar until it depletes to 0 it will then start to deplete the second stamina bar and so on. Now, that is how it was intended to happen, but I'm not able get it to function that way. Here is the jsfiddle for it, whenever I click on the attack button multiple times the stamina bar is lagging up and once the stamina bar is complete it will still deplete the stamina bar and regnerate itself again. You have to try the jsfiddle to understand what I'm talking about.
HTML
<body>
<div id="container">
<div class="hBar"> <div class="health"></div></div><!--hbar -->
<div class="sBar">
<div class="s3">
<div class="s2">
<div class="s1">
</div><!--s1 -->
</div><!--s2 -->
</div><!--s3 -->
</div><!--sBar -->
<div class="attack">attack</div>
</div><!--container -->
</body>
CSS
*{ margin:0px; padding:0px;}
.hBar{width:400px; height:40px; border:1px solid grey; margin-bottom:20px;}
.health{background:green;width:100%; height:100%;}
.sBar{ width:400px; height:40px; border:1px solid grey; margin-bottom:20px;}
.s3{ width:100%; height:100%; background:red;}
.s2{width:100%; height:100%; background:orange;}
.s1{width:100%; height:100%; background:yellow;}
#container{background:white; width:80%; padding:10px; margin:auto;}
body{background:#CCC;}
.attack{ border-radius:90px; border:black solid 1px; height:75px; width:75px; text-align:center; line-height:75px;}
.attack:hover{cursor:pointer;}
Javascript
$(document).ready(function () {
// one , two, and three variables are collecting the stamina bars
var one = $('.s1');
var two = $('.s2');
var three = $('.s3');
var oneWidth = one.width();
var twoWidth = two.width();
var threeWidth = three.width();
var stam = $('.sBar').width();
var damage;
var subtractHealth;
var num;
$('.attack').click(function () {
// timer is supposed to be the variable for a setInterval function
let timer;
// damage is supposed to take away the stamina
damage = 100;
// This function is supposed to stop the interval and the animation done on the
// stamina bars
function stopAnimate() {
clearInterval(timer);
one.stop();
two.stop();
three.stop();
}
// if the first and the second stamina bar is below 0, then add subtract the width to .s3
if (oneWidth <= 0 && twoWidth <= 0) {
subtractHealth = $('.s3').width() - damage;
three.animate({
'width': subtractHealth
}, 'fast');
// if the first stamina bar is less than 0, the subtract the width of .s2
} else if (oneWidth <= 0) {
subtractHealth = $('.s2').width() - damage;
two.animate({
'width': subtractHealth
}, 'fast');
// if the first stamina bar is not below 0 then run the content in this
} else {
subtractHealth = $('.s1').width() - damage;
one.animate({
'width': subtractHealth
}, 'fast');
}
// regenerates all the three stamina bars with the animate method
function regenerate(stam1, stam2, stam3) {
stam1.animate({
'width': stam
}, 1000, function () {
if (stam1.width() == stam) {
stam2.animate({
'width': stam
}, 1000, function () {
if (stam2.width() == stam) {
stam3.animate({
'width': stam
}, 1000)
}// if stam2
});//stam2.animate
}//if stam.width()
})//stam1.animate
setTimeout(stopAnimate(), 5000); //end function
}; //end regenerate
// run setInterval and assign the method to timer
timer = setInterval(regenerate(one, two, three), 1000);
}); //end click
}); //end ready
I'm not 100% certain that i have the effect you are after, but if not I think you should be able to modify this code to get the result you seek. If you would like additional assistance, drop a comment and I will be happy to see what I can do.
var staminaMax = 1000;
var staminaCurrent = staminaMax;
var staminaHealInterval;
var staminaTick = 100;
var staminHealPerTick = 10;
var $sBar3 = $(".sBar .sBarStatus.s3");
var $sBar2 = $(".sBar .sBarStatus.s2");
var $sBar1 = $(".sBar .sBarStatus.s1");
var healStamina = function() {
staminaCurrent = Math.min(staminaCurrent + staminHealPerTick, staminaMax);
var rawPct = staminaCurrent / staminaMax;
var s1Pct = (function() {
if (rawPct <= (2 / 3)) { return 0; }
return (rawPct - (2 / 3)) / (1 / 3);
})();
var s2Pct = (function() {
if (rawPct <= (1 / 3)) { return 0; }
if (rawPct >= (2 / 3)) { return 1; }
return (rawPct - (1 / 3)) / (1 / 3);
})();
var s3Pct = (function() {
if (rawPct >= (1 / 3)) { return 1; }
return (rawPct - (0 / 3)) / (1 / 3);
})();
$sBar3.css("width", 100 * s3Pct + "%");
$sBar2.css("width", 100 * s2Pct + "%");
$sBar1.css("width", 100 * s1Pct + "%");
if (staminaCurrent >= staminaMax) {
clearInterval(staminaHealInterval);
staminaHealInterval = null;
}
};
var dingStamina = function(amount) {
staminaCurrent = Math.max(staminaCurrent - amount, 0);
if (!staminaHealInterval) {
staminaHealInterval = setInterval(healStamina, staminaTick);
}
}
$('.attack').click(function() {
dingStamina(100);
});
* {
margin: 0px;
padding: 0px;
}
.hBar {
width: 400px;
height: 10px;
border: 1px solid grey;
margin-bottom: 20px;
}
.health {
background: green;
width: 100%;
height: 100%;
}
.sBar {
width: 400px;
height: 10px;
border: 1px solid grey;
margin-bottom: 20px;
position: relative;
}
.sBar .sBarStatus {
position: absolute;
width: 100%;
height: 100%;
}
.s3 {
background: red;
}
.s2 {
background: orange;
}
.s1 {
background: yellow;
}
#container {
background: white;
width: 80%;
padding: 10px;
margin: auto;
}
body {
background: #CCC;
}
.attack {
border-radius: 90px;
border: black solid 1px;
height: 75px;
width: 75px;
text-align: center;
line-height: 75px;
}
.attack:hover {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<div class="hBar">
<div class="health"></div>
</div>
<div class="sBar">
<div class="sBarStatus s3"></div>
<div class="sBarStatus s2"></div>
<div class="sBarStatus s1"></div>
</div>
<div class="attack">attack</div>
</div>
I'm struggling to find a solution to this and wonder if anyone can help.
I'd like to make a page where an image would disappear over time revealing another image. I'm hoping to achieve this by using the updatesecond/getseconds function. So essentially it would act as a clock, the more minutes/seconds have passed the more it disappears, and have it cycle. For example at the beginning of the day it would be a full image, at 12 it would be half, and at 24hours it would be gone, and repeat. I figure it would be an if else function about the percentage of the page that's left, I just can't figure out how to word it.
Is this possible at all? Any help would be greatly appreciated. Thanks!
Here is the code I'm working with so far. Thank you in advance.
body
{
background-color: #FFF;
padding: 2%;
color: #ccc;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 1em;
}
a
{
color: #FFF;
text-decoration: none;
}
a:hover
{
color: #DCE808;
text-decoration: underline;
}
#mosaic
{
/* background-color: yellow;
font-size: 500px;
color: black;
height: 1310px;
width: 2000px; */
background-image: url('tomorrow4.png');
}
#mosaic span.hover
{
/* background-color: blue;
font-size: 500px;
color: white;
height: 1310px;
width: 2000px;
left: 100px;*/
float: left;
background-image: url('today4.png');
}
and javascript
$(document).ready(function() {
var width = 1400;
var height = 724;
count = 0;
elements = new Array();
var el = $('#mosaic');
el.width(width).height(height);
var horizontal_pieces = 100;
var vertical_pieces = 100;
total_pieces = horizontal_pieces * vertical_pieces;
var box_width = width / horizontal_pieces;
var box_height = height / vertical_pieces;
var vertical_position = 0;
for (i=0; i<total_pieces; i++)
{
var tempEl = $('<span class="hover" id="hover-' + i + '">
</span>');
var horizontal_position = (i % horizontal_pieces) * box_width;
if(i > 0 && i % horizontal_pieces == 0)
{
vertical_position += box_height;
}
tempEl.css('background-position', '-' + horizontal_position + 'px
-' + vertical_position + 'px');
el.append(tempEl);
elements.push(tempEl);
}
elements = shuffleArray(elements);
$('#mosaic .hover').width(box_width).height(box_height);
setInterval(toggleDisplay, 100);
});
function toggleDisplay()
{
var tempEl = elements[count];
var opacity = tempEl.css('opacity');
if(opacity == 0)
{
tempEl.animate({ opacity: 1 })
}
else
{
tempEl.animate({ opacity: 0 })
}
count = (count + 1) % total_pieces;
}
/* shuffleArray source:
http://stackoverflow.com/questions/2450954/how-to-randomize-a-
javascript-array#12646864 */
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor() * (i + 1);
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
Do you mean something like this? http://jsfiddle.net/1r5qer56/
I used 4 sectors (as skewY tends to screw up over 90 degrees) and had them set to a size relative to the amount of minutes that have passed since midnight.
If you want to test it, just put a custom number in for time.
My code is below:
HTML
<ul class='pie'>
<li class='slice tr'><div class='slice-contents'></div></li>
<li class='slice br'><div class='slice-contents'></div></li>
<li class='slice bl'><div class='slice-contents'></div></li>
<li class='slice tl'><div class='slice-contents'></div></li>
<ul>
CSS
.pie {
position: relative;
margin: 1em auto;
border: dashed 1px;
padding: 0;
width: 32em; height: 32em;
border-radius: 50%;
list-style: none;
background-image: url('http://lorempixel.com/output/animals-q-c-512-512-4.jpg');
}
.slice {
overflow: hidden;
position: absolute;
top: 0; right: 0;
width: 50%; height: 50%;
transform-origin: 0% 100%;
}
.slice.tr {
transform: rotate(0deg) skewY(-0deg);
}
.slice.br {
transform: rotate(90deg) skewY(0deg);
}
.slice.bl {
transform: rotate(180deg) skewY(0deg);
}
.slice.tl {
transform: rotate(270deg) skewY(0deg);
}
.slice-contents {
position: absolute;
left: -100%;
width: 200%; height: 200%;
border-radius: 50%;
background: lightblue;
}
.slice.tr .slice-contents {
transform: skewY(0deg); /* unskew slice contents */
}
.slice.br .slice-contents {
transform: skewY(0deg); /* unskew slice contents */
}
.slice.bl .slice-contents {
transform: skewY(0deg); /* unskew slice contents */
}
.slice.tl .slice-contents {
transform: skewY(0deg); /* unskew slice contents */
}
JS+jQuery
updateClock();
setInterval(function(){updateClock();}, 60000);//check for updates once per minute
function updateClock(){
var dt = new Date();
var time = (dt.getHours() * 60) + dt.getMinutes();//number of minutes since 00.00
var timeToDegrees = time / 4;//1440 minutes in 24hours, 360 degrees in a circle. 1440 / 4 = 360
if(timeToDegrees < 90){//deal with top right sector
$('.slice.tr').css('transform', 'rotate('+timeToDegrees+'deg) skewY(-'+timeToDegrees+'deg)');
$('.slice.tr .slice-contents').css('transform', 'skewY('+timeToDegrees+'deg)');
}
else if(timeToDegrees < 180){//deal with bottom right sector
var localDeg = timeToDegrees - 90;
$('.slice.tr').eq(0).css('transform', 'rotate(90deg) skewY(-90deg)');
$('.slice.tr .slice-contents').css('transform', 'skewY(90deg)');
$('.slice.br').css('transform', 'rotate('+(90+localDeg)+'deg) skewY(-'+localDeg+'deg)');
$('.slice.br .slice-contents').css('transform', 'skewY('+localDeg+'deg)');
}
else if(timeToDegrees < 270){//deal with bottom left sector
var localDeg = timeToDegrees - 180;
$('.slice.tr').css('transform', 'rotate(90deg) skewY(-90deg)');
$('.slice.tr .slice-contents').css('transform', 'skewY(90deg)');
$('.slice.br').css('transform', 'rotate(180deg) skewY(-90deg)');
$('.slice.br .slice-contents').css('transform', 'skewY(90deg)');
$('.slice.bl').css('transform', 'rotate('+(180+localDeg)+'deg) skewY(-'+localDeg+'deg)');
$('.slice.bl .slice-contents').css('transform', 'skewY('+localDeg+'deg)');
}
else if(timeToDegrees <= 360){//deal with top left sector
var localDeg = timeToDegrees - 270;
$('.slice.tr').css('transform', 'rotate(90deg) skewY(-90deg)');
$('.slice.tr .slice-contents').css('transform', 'skewY(90deg)');
$('.slice.br').css('transform', 'rotate(90deg) skewY(-90deg)');
$('.slice.br .slice-contents').css('transform', 'skewY(90deg)');
$('.slice.bl').css('transform', 'rotate(270deg) skewY(-90deg)');
$('.slice.bl .slice-contents').css('transform', 'skewY(90deg)');
$('.slice.tl').css('transform', 'rotate('+(270+localDeg)+'deg) skewY(-'+localDeg+'deg)');
$('.slice.tl .slice-contents').css('transform', 'skewY('+localDeg+'deg)');
}
}
Taking a look at the code, from what I gather, you're looking for a picture that is covered with another picture, proportional to the length of the day in seconds. Like one picture sliding over another? Like this picture:
Take a look at the jsBin I've created here http://jsbin.com/xevinakihe/edit?html,css,js,output
The meat of the code is the timing and height adjustment:
function setCoverHeight() {
var d = new Date();
var curSecs = d.getHours() * 3600 + d.getMinutes() * 60 + d.getSeconds();
var coverHeight = curSecs * 100 / (24 * 3600);
$('.cover').height(coverHeight + '%');
if (curSecs < 24 * 3600) {
setTimeout(setCoverHeight, 1000);
console.log(coverHeight);
} else {
// reset the cover height to 0%
$('.cover').height(0);
// swap the cover image to the bottom
$('.bottom').css('backround-image', $('.cover').css('background-image'));
// set a new cover image
// ... get from Ajax, array, etc
}
}
setCoverHeight();
That is adjusting the HTML:
<div class="wrapper">
<div class="cover"></div>
<div class="bottom"></div>
</div>
Eventually the day will run out and the cover should be swapped with the bottom image, so that you can cycle through individual daily pictures (ex. 'today.jpg' and 'tomorrow.jpg')
Hope that helps!