is it possible to reuse this javascript
<script>
var speed = 100;
var gold = 0;
gold = parseFloat(gold.toFixed(2));
var production = 10;
production = parseFloat(production.toFixed(0));
var price = 100;
price = parseFloat(price.toFixed(2));
document.getElementById("speed").innerHTML=speed;
document.getElementById("gold").innerHTML = gold;
document.getElementById("production").innerHTML=production;
document.getElementById("price").innerHTML=price;
function dig() {
var elem = document.getElementById("bar");
var width = 0;
var id = setInterval(frame, speed);
function frame() {
if (width >= 100) {
clearInterval(id);
elem.style.width = '0%';
gold = gold + production;
gold = parseFloat(gold.toFixed(2));
document.getElementById("dig").disabled = false;
document.getElementById("gold").innerHTML = gold;
if (price <= gold) {
document.getElementById("upgrade").disabled = false;
} else {
document.getElementById("upgrade").disabled = true;
}
} else {
width++;
elem.style.width = width + '%';
document.getElementById("dig").disabled = true;
}
}
}
$(document).ready(function priceUpgrade() {
if (price <= gold) {
document.getElementById("upgrade").disabled = false;
} else {
document.getElementById("upgrade").disabled = true;
}
});
$(document).ready(function upgrade(){
$("#upgrade").click(function(){
speed = speed - 10;
gold = gold - price;
gold = parseFloat(gold.toFixed(2));
production += production * 0.10;
production = parseFloat(production.toFixed(0));
price += price * 0.50;
price = parseFloat(price.toFixed(2));
document.getElementById("speed").innerHTML=speed;
document.getElementById("gold").innerHTML=gold;
document.getElementById("production").innerHTML=production;
document.getElementById("price").innerHTML=price;
if (price <= gold) {
document.getElementById("upgrade").disabled = false;
} else {
document.getElementById("upgrade").disabled = true;
}
});
});
</script>
with a new value in the variables speed, gold and production for each new html line of these
<div id="speed">100</div>
<div class="row">
<div class="col-md-2">
<div id="production"></div>
<button type="button" class="btn btn-success" onclick="dig()" id="dig">Gull Sil</button>
</div>
<div class="col-md-7">
<div id="progress">
<div id="bar"></div>
</div>
</div>
<div class="col-md-3">
<div id="price"></div>
<button type="button" class="btn btn-warning" onclick="upgrade()" id="upgrade">Oppgrader</button>
</div>
</div>
so each time a call speed[3] or dig(3) both the variables and the functions response different to each key=>value in an array or some how??
maybe var speed {1:10,2:30,3:70,4:150};
and dig([1,2,3,4]);
Related
Im creating a guessing game and the user has 5 attempts to make the correct guess. I want to save their previous guesses (inputs) to show it to them. I have been using the snippet below to save one attempt when the user types into an <input> field, but how can I save the next 4 attempts in new variables such as userGuess2, userGuess3, etc.
var userGuess = document.getElementById("inputField").value;
$('#previousGuesses').text(userGuess);
Ok then let's pretend this is your input
<input type="text" id="inputField">
You can create an index that will increment everytime the users presses enter to save another answer
var i=1;
And the id name your autogenerated spans will have
var name = "previousGuesses";
Now on your function you will save the value when the user presses enter like you described and when that happens it will create a new span element where it will display the value stored
function myFunction(){
$("#inputField").keypress(function( event ) {
if ( event.which == 13 || event.which == 9) {
var userGuess = document.getElementById("inputField").value;//get value of the answer
var span = document.createElement('SPAN');//create a new span
span.innerHTML = userGuess + "<br>";//answer value goes here
span.id = name+i;//this is the id of your new span, remember ids are unique so we attach var i to the name var we declared before
document.body.appendChild(span);
//$('#previousGuesses'+i).text(userGuess);
i++;
}
});
}
now call your function
myFunction();
https://jsfiddle.net/kenpy/m16bojhg/4/
You can just simply add an element for the user's last attempts and add to it.
f(guessCount === 1) {
guesses.textContent = 'Previous guesses: ';
}
guesses.textContent += userGuess + ' ';
var randomNumber = Math.floor(Math.random() * 100) + 1;
var guesses = document.querySelector('.guesses');
var lastResult = document.querySelector('.lastResult');
var lowOrHi = document.querySelector('.lowOrHi');
var guessSubmit = document.querySelector('.guessSubmit');
var guessField = document.querySelector('.guessField');
var guessCount = 1;
var resetButton;
guessField.focus();
function checkGuess() {
var userGuess = Number(guessField.value);
if(guessCount === 1) {
guesses.textContent = 'Previous guesses: ';
}
guesses.textContent += userGuess + ' ';
if(userGuess === randomNumber) {
lastResult.textContent = "Good job! You win!";
lastResult.style.backgroundColor = 'green';
lowOrHi.textContent = '';
setGameOver();
} else if(guessCount === 10) {
lastResult.textContent = 'Hahaha You suck!';
lowOrHi.textContent = '';
setGameOver();
} else {
lastResult.textContent = "Oops! You're Wrong!";
lastResult.style.backgroundColor = 'red';
if(userGuess < randomNumber) {
lowOrHi.textContent = 'Last guess was too low!';
} else if(userGuess > randomNumber) {
lowOrHi.textContent = 'Last guess was too high!';
}
}
guessCount++;
guessField.value = '';
guessField.focus();
}
guessSubmit.addEventListener('click', checkGuess);
console.log('cheat is: ' + randomNumber);
function setGameOver() {
guessField.disabled = true;
guessSubmit.disabled = true;
resetButton = document.createElement('button');
resetButton.textContent = 'Play Again?';
document.body.appendChild(resetButton);
resetButton.addEventListener('click', resetGame);
}
function resetGame() {
guessCount = 1;
var resetParas = document.querySelectorAll('.resultParas p');
for(var i = 0 ; i < resetParas.length ; i++) {
resetParas[i].textContent = '';
}
resetButton.parentNode.removeChild(resetButton);
guessField.disabled = false;
guessSubmit.disabled = false;
guessField.value = '';
guessField.focus();
lastResult.style.backgroundColor = 'white';
randomNumber = Math.floor(Math.random() * 100) + 1;
}
body{
background-image: linear-gradient(to left top, #c6fced, #a3efda, #7fe3c7, #54d5b3, #00c89f);
color: #2F3139;
margin: 10rem auto;
height:50vh;
}
h1 {
font-size: 1.5rem;
}
.lastResult {
color: white;
padding: 3px;
}
button {
margin-left:3rem ;
}
<h3 class="display-4 text-center text-muted text-capitalize"></h3>
<div class="container">
<div class="row">
<div class="col-md-6 ">
<h1 class="text-muted text-capitalize">
<span class="text-primary">JavaScript</span> Number guessing game</h1>
<p class="lead">Simply enter a number between 1 - 100 then click the button</p>
</div>
<div class="col-md-6">
<div class="mt-4 d-inline-block">
<div class="form">
<label for="guessField">Guess a number : </label><input type="text" id="guessField" class="guessField">
<input type="submit" value="Submit guess" class="guessSubmit">
</div>
<div class="resultParas text-center lead">
<p class="guesses"></p>
<p class="lastResult"></p>
<p class="lowOrHi"></p>
</div>
</div>
</div> </div>
</div>
Resource
JavaScript number guessing game
I have this audio player script that plays audio files, but i don't know how to play the files individually based on id from mysql database. I have a datatable and all the files listed there with a play button to make an idea. Thanks
Codepen audio player script:
https://codepen.io/abxlfazl/pen/YzGEVRP
Here is the audio script:
PHP:
<?php
$qnm = $db->query("SELECT * FROM `".RDCP_PREFIX."muzica` WHERE uid = ".$uid." ");
while ($row = $db->fetch($qnm)) {
$id = $row['mid']; // music id
$locatiem = $row['locatie'];
$numeclubs = $row['numeclub'];
$numecoregrafiem = $row['numecoregrafie'];
$piesa = str_replace("muzica/", "", $locatiem); // music file track
?>
HTML:
<div class="modal plyer fade delmusic<?php echo $id;?>" tabindex="-1" id="delmusic<?php echo $id; ?>"
track="<?php echo $id;?>" aria-labelledby="myDefaultModalLabel">
<div class="container" style="margin-top: 332px;display: flex;">
<div class="player">
<div class="player__header">
<div class="player__img player__img--absolute slider">
<button class="player__button player__button--absolute--nw playlist">
<img src="../../../dt/app-assets/images/elements/musicplayer/playlist.svg" alt="playlist-icon">
</button>
<button class="player__button player__button--absolute--center play">
<img src="../../../dt/app-assets/images/elements/musicplayer/play.svg" alt="play-icon">
<img src="../../../dt/app-assets/images/elements/musicplayer/pause.svg" alt="pause-icon">
</button>
<div class="slider__content">
<img class="img slider__img" src="http://physical-authority.surge.sh/imgs/1.jpg" alt="cover">
</div>
</div>
<div class="player__controls">
<button class="player__button back">
<img class="img" src="../../../dt/app-assets/images/elements/musicplayer/back.svg" alt="back-icon">
</button>
<p class="player__context slider__context">
<strong class="slider__name"></strong>
<span class="player__title slider__title"></span>
</p>
<button class="player__button next">
<img class="img" src="../../../dt/app-assets/images/elements/musicplayer/next.svg" alt="next-icon">
</button>
<div class="progres">
<div class="progres__filled"></div>
</div>
</div>
</div>
<ul class="player__playlist list">
<li class="player__song s<?php echo $id;?>">
<img class="player__img img" src="http://physical-authority.surge.sh/imgs/1.jpg" alt="cover">
<p class="player__context">
<b class="player__song-name"><?php echo $numecoregrafiem; ?></b>
<span class="flex">
<span class="player__title"><?php echo $numeclubs; ?></span>
</span>
</p>
<audio class="audio" src="<?php echo "dt/pagini/momente/momente/".$locatiem; ?>"></audio>
</li>
</ul>
</div>
</div>
</div>
Javascript:
const bgBody = ["#e5e7e9", "#ff4545", "#f8ded3", "#ffc382", "#f5eda6", "#ffcbdc", "#dcf3f3"];
const body = document.body;
const player = document.querySelector(".player");
const playerHeader = player.querySelector(".player__header");
const playerControls = player.querySelector(".player__controls");
const playerPlayList = player.querySelectorAll(".player__song");
const playerSongs = player.querySelectorAll(".audio");
const playButton = player.querySelector(".play");
const nextButton = player.querySelector(".next");
const backButton = player.querySelector(".back");
const playlistButton = player.querySelector(".playlist");
const slider = player.querySelector(".slider");
const sliderContext = player.querySelector(".slider__context");
const sliderName = sliderContext.querySelector(".slider__name");
const sliderTitle = sliderContext.querySelector(".slider__title");
const sliderContent = slider.querySelector(".slider__content");
const sliderContentLength = playerPlayList.length - 1;
const sliderWidth = 100;
let left = 0;
let count = 0;
let song = playerSongs[count];
let isPlay = false;
const pauseIcon = playButton.querySelector("img[alt = 'pause-icon']");
const playIcon = playButton.querySelector("img[alt = 'play-icon']");
const progres = player.querySelector(".progres");
const progresFilled = progres.querySelector(".progres__filled");
let isMove = false;
function closePlayer() {
playerHeader.classList.remove("open-header");
playerControls.classList.remove("move");
slider.classList.remove("open-slider");
}
function next(index) {
count = index || count;
if (count == sliderContentLength) {
count = count;
return;
}
left = (count + 1) * sliderWidth;
left = Math.min(left, (sliderContentLength) * sliderWidth);
sliderContent.style.transform = `translate3d(-${left}%, 0, 0)`;
count++;
run();
}
function back(index) {
count = index || count;
if (count == 0) {
count = count;
return;
}
left = (count - 1) * sliderWidth;
left = Math.max(0, left);
sliderContent.style.transform = `translate3d(-${left}%, 0, 0)`;
count--;
run();
}
function changeSliderContext() {
sliderContext.style.animationName = "opacity";
sliderName.textContent = playerPlayList[count].querySelector(".player__title").textContent;
sliderTitle.textContent = playerPlayList[count].querySelector(".player__song-name").textContent;
if (sliderName.textContent.length > 16) {
const textWrap = document.createElement("span");
textWrap.className = "text-wrap";
textWrap.innerHTML = sliderName.textContent + " " + sliderName.textContent;
sliderName.innerHTML = "";
sliderName.append(textWrap);
}
if (sliderTitle.textContent.length >= 18) {
const textWrap = document.createElement("span");
textWrap.className = "text-wrap";
textWrap.innerHTML = sliderTitle.textContent + " " + sliderTitle.textContent;
sliderTitle.innerHTML = "";
sliderTitle.append(textWrap);
}
}
function selectSong() {
song = playerSongs[count];
for (const item of playerSongs) {
if (item != song) {
item.pause();
item.currentTime = 0;
}
}
if (isPlay) song.play();
}
function run() {
changeSliderContext();
selectSong();
}
function playSong() {
if (song.paused) {
song.play();
playIcon.style.display = "none";
pauseIcon.style.display = "block";
}else{
song.pause();
isPlay = false;
playIcon.style.display = "";
pauseIcon.style.display = "";
}
}
function progresUpdate() {
const progresFilledWidth = (this.currentTime / this.duration) * 100 + "%";
progresFilled.style.width = progresFilledWidth;
if (isPlay && this.duration == this.currentTime) {
next();
}
if (count == sliderContentLength && song.currentTime == song.duration) {
playIcon.style.display = "block";
pauseIcon.style.display = "";
isPlay = false;
}
}
function scurb(e) {
// If we use e.offsetX, we have trouble setting the song time, when the mousemove is running
const currentTime = ( (e.clientX - progres.getBoundingClientRect().left) / progres.offsetWidth ) * song.duration;
song.currentTime = currentTime;
}
function durationSongs() {
let min = parseInt(this.duration / 60);
if (min < 10) min = "0" + min;
let sec = parseInt(this.duration % 60);
if (sec < 10) sec = "0" + sec;
const playerSongTime = `${min}:${sec}`;
}
changeSliderContext();
// add events
sliderContext.addEventListener("animationend", () => sliderContext.style.animationName ='');
playlistButton.addEventListener("click", closePlayer);
nextButton.addEventListener("click", () => {
next(0)
});
backButton.addEventListener("click", () => {
back(0)
});
playButton.addEventListener("click", () => {
isPlay = true;
playSong();
});
playerSongs.forEach(song => {
song.addEventListener("loadeddata" , durationSongs);
song.addEventListener("timeupdate" , progresUpdate);
});
progres.addEventListener("pointerdown", (e) => {
scurb(e);
isMove = true;
});
document.addEventListener("pointermove", (e) => {
if (isMove) {
scurb(e);
song.muted = true;
}
});
document.addEventListener("pointerup", () => {
isMove = false;
song.muted = false;
});
playerPlayList.forEach((item, index) => {
item.addEventListener("click", function() {
if (index > count) {
next(index - 1);
return;
}
if (index < count) {
back(index + 1);
return;
}
});
});
You could put the track ID into an attribute like "data-track" then retrieve it and send out an ajax request to a php page which will do your DB query and return the info you want.
// User selects track to play
$(".track").on('click', function(e){
track = $(this).data("track");
var data = {
trackId: track
};
$.ajax({
url: 'getTrack.php',
type: 'post',
data: data,
}).done(function(result){
// parse data from response and load your player's modal
}).fail(function(data){
// Uh-oh!
}).always(function(){
// Do something
});
});
This is supposed to be a dice game where 2 people click to roll dice and they add what they get until they reach the goal. Their score resets if they roll over 9 though. Images of dice are supposed to pop up and show what they rolled. I know the images are not on here but it still shows that there should an image there with the error symbol. I am having trouble with the second image not showing up which should come from the SetPic2 function. Any help would be appreciated. Also, the PASS buttons are supposed the pass the person's turn to the other player but the main problem is the images.
//console.log("file loaded");
//var p1Button = document.getElementById("p1");
var p1Button = document.querySelector("#p1");
var p2Button = document.querySelector("#p2");
var P1Pass = document.querySelector("P1Pass");
var P2Pass = document.querySelector("P2Pass");
var setButton = document.querySelector("#set");
var resetButton = document.querySelector("#reset");
var diceImage = document.querySelector("img");
var diceImage2 = document.querySelector("img2");
var p1Total = document.querySelector("#p1score");
var p2Total = document.querySelector("#p2score");
var targetScore = document.querySelector("#tscore");
var newScore = document.querySelector("#newtarget");
var num = 0,
num2 = 0,
p1val = 0,
p2val = 0,
target;
var playgame = true;
target = Number(targetScore.textContent); //convert the string to num
p1Button.addEventListener("click", function() {
if (playgame) {
//Math.random() --> return a value between 0 & 1
num = Math.floor((Math.random() * 6) + 1);
num2 = Math.floor((Math.random() * 6) + 1);
p1val = p1val + num + num2;
p1Total.textContent = p1val;
setButton.disabled = true;
p1Button.disabled = true;
p2Button.disabled = false;
setPic(num);
setPic2(num2);
if (num + num2 > 9) {
p1val = 0;
}
if (p1val >= target) {
playgame = false;
p1Total.classList.add("winner");
stopGame();
}
}
});
p2Button.addEventListener("click", function() {
if (playgame) {
//Math.random() --> return a value between 0 & 1
num = Math.floor((Math.random() * 6) + 1);
num2 = Math.floor((Math.random() * 6) + 1);
p2val = p2val + num + num2;
p2Total.textContent = p2val;
setButton.disabled = true;
p1Button.disabled = false;
p2Button.disabled = true;
setPic(num);
setPic2(num2);
if (num + num2 > 9) {
p2val = 0;
}
if (p2val >= target) {
playgame = false;
p2Total.classList.add("winner");
stopGame();
}
}
});
/*P1Pass.addEventListener("click", function(){
p1Button.disabled= true;
p2Button.disabled = false;
});
P2Pass.addEventListener("click", function(){
p1Button.disabled = false;
p2Button.disabled = true;
});*/
setButton.addEventListener("click", function() {
targetScore.textContent = newScore.value;
target = Number(targetScore.textContent);
setButton.disabled = true;
newScore.disabled = true;
});
resetButton.addEventListener("click", function() {
p1Button.disabled = false;
p2Button.disabled = true;
p1Total.textContent = "0";
p2Total.textContent = "0";
targetScore.textContent = "25";
setButton.disabled = false;
newScore.disabled = false;
p1Total.classList.remove("winner");
p2Total.classList.remove("winner");
playgame = true;
p1val = 0;
p2val = 0;
target = 25;
});
function stopGame() {
p1Button.disabled = true;
p2Button.disabled = true;
setButton.disabled = true;
newScore.disabled = true;
}
function setPic(val) {
if (val == 1) {
diceImage.src = "1.png";
} else if (val == 2) {
diceImage.src = "2.png";
} else if (val == 3) {
diceImage.src = "3.png";
} else if (val == 4) {
diceImage.src = "4.png";
} else if (val == 5) {
diceImage.src = "5.png";
} else if (val == 6) {
diceImage.src = "6.png";
}
}
function setPic2(val2) {
if (val2 == 1) {
diceImage2.src = "1.png";
} else if (val2 == 2) {
diceImage2.src = "2.png";
} else if (val2 == 3) {
diceImage2.src = "3.png";
} else if (val2 == 4) {
diceImage2.src = "4.png";
} else if (val2 == 5) {
diceImage2.src = "5.png";
} else if (val2 == 6) {
diceImage2.src = "6.png";
}
}
.winner {
color: green;
background-color: yellow;
}
;
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap
.min.css" integrity="sha384-
Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="gamestyle.css">
<title>Dice Game</title>
</head>
<body>
<div class="container">
<br>
<h1> <span id="p1score">0</span> vs. <span id="p2score">0</span> </h1>
<br>
<p>Target-Score: <span id="tscore">25</span></p>
<br>
<button class="btn btn-success" id="p1"> Player One </button>
<button class="btn btn-warning" id="p2"> Player Two </button>
<br><br>
<button class="btn btn-secondary" id="P1Pass">PASS</button>
<button class="btn btn-secondary" id="P2Pass">PASS</button>
<br><br> New Target: <input type="number" id="newtarget">
<br><br>
<button class="btn btn-primary" id="set"> Set </button>
<button class="btn btn-danger" id="reset"> Reset </button>
<br><br>
<img src="">
<img src="">
</div>
<script src="gamefunction.js"></script>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-
J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min
.js" integrity="sha384-
Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.m
in.js" integrity="sha384-
wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>
Your selector will not finding your second image element.
var diceImage2 = document.querySelector("img2");
You could give your images IDs and reference them directly:
HTML
<img id="die1" src="" />
<img id="die2" src="" />
JS
var diceImage1 = document.getElementById('die1');
var diceImage2 = document.getElementById('die2');
I want to take some text from the HTML page and tweet it out.
Here is my HTML page -
function change() {
quotes = ["Naam toh suna hi hoga", "Mogambo Khush Hua", "Kitne aadmi the?"];
auth = ["Raj", "Mogambo", "Gabbar"];
min = 0;
max = 3;
num = Math.floor(Math.random() * (max - min)) + min;
q = quotes[num]
document.getElementById("quote").innerHTML = quotes[num];
document.getElementById("author").innerHTML = auth[num];
if (num == 0) {
document.getElementById("bod").style.color = 'white';
document.body.style.backgroundColor = 'green';
document.getElementById("another").style.backgroundColor = 'green';
document.getElementById("tweet").style.backgroundColor = 'green';
}
if (num == 1) {
document.getElementById("bod").style.color = 'black';
document.body.style.backgroundColor = 'yellow';
document.getElementById("another").style.backgroundColor = 'yellow';
document.getElementById("another").style.color = 'black';
document.getElementById("tweet").style.color = 'black';
document.getElementById("tweet").style.backgroundColor = 'yellow';
}
if (num == 2) {
document.getElementById("bod").style.color = 'white';
document.body.style.backgroundColor = 'blue';
document.getElementById("another").style.backgroundColor = 'blue';
document.getElementById("tweet").style.backgroundColor = 'blue';
}
}
function twitter() {
text = document.getElementById('quote').innerHTML;
// document.getElementById('tw').innerHTML = text;
$('.twitter-button').attr("href", 'https://twitter.com/intent/tweet?text=' + text);
};
<body id='bod'>
<h1>Quotes</h1>
<div class='text'>
<p id='quote'>You're fired!</p>
<br>
<p id='author'>Vince McMahon</p>
<button id='another' class='btn btn-primary' onclick='change()'>Another Quote</button>
<br>
<br>
<a class="twitter-button" href="https://twitter.com/intent/tweet?text=" target="_blank">
<button type="button" onclick='twitter()' class="btn btn-primary" id='tw'>Tweet!</button>
</a>
Whenever I click on the tweet button, there is no text on the twitter page. Just a blank box.
Link to Codepen - https://codepen.io/pranavgoel25/pen/ZybNRv?editors=1010
I have tweeked a code bit:
var quotes = ["Naam toh suna hi hoga","Mogambo Khush Hua","Kitne aadmi the?"];
function change(){
auth = ["Raj","Mogambo","Gabbar"];
min = 0;
max = 3;
num = Math.floor(Math.random() * (max - min)) + min;
q = quotes[num]
document.getElementById("quote").innerHTML = quotes[num];
document.getElementById("author").innerHTML = auth[num];
document.getElementById('twitterBtn').setAttribute("href", 'https://twitter.com/intent/tweet?text=twee' + quotes[num]);
if (num == 0){
document.getElementById("bod").style.color='white';
document.body.style.backgroundColor = 'green';
document.getElementById("another").style.backgroundColor='green';
document.getElementById("tweet").style.backgroundColor='green';
}
if (num == 1){
document.getElementById("bod").style.color='black';
document.body.style.backgroundColor = 'yellow';
document.getElementById("another").style.backgroundColor='yellow';
document.getElementById("another").style.color='black';
document.getElementById("tweet").style.color='black';
document.getElementById("tweet").style.backgroundColor='yellow';
}
if (num == 2){
document.getElementById("bod").style.color='white';
document.body.style.backgroundColor = 'blue';
document.getElementById("another").style.backgroundColor='blue';
document.getElementById("tweet").style.backgroundColor='blue';
}
}
window.onload = function(){
document.getElementById('twitterBtn').setAttribute("href", 'https://twitter.com/intent/tweet?text=twee' + quotes[0]);
}
Working Demo:
https://codepen.io/anon/pen/BZjQBe?editors=1010
I'm building a Pomodoro Clock to improve my JavaScript, but I have a few issues. For starters, the increment/decrement buttons for the break do not update the time in the display. Secondly, the Session time doesn't restart after the first break period. Can anyone, please, advise me of where I went wrong?
The HTML:
<html>
<head>
<title>David Hall - Pomodoro Clock Zipline</title>
<link href="https://fonts.googleapis.com/css?family=Orbitron" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link href="main.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
<h1 class="center">Pomodoro Clock</h1>
<div class="row">
<div class="center">
<div class="col-sm-6">Break Length</div>
<div class="col-sm-6">Work Length</div>
<div class="col-sm-6" id="center">
<div class="btn-group">
<button type="button" class="btn btn-success" id="decreaseBreak"><span class="glyphicon glyphicon-menu-left"></span>
<button type="button" class="btn btn-success"><span id="breakTime">5</span>
<button type="button" class="btn btn-success btn" id="increaseBreak"><span class="glyphicon glyphicon-menu-right"></span></div>
</div>
<div class="col-sm-6">
<div class="btn-group">
<button type="button" class="btn btn-success" id="decreaseWork"><span class="glyphicon glyphicon-menu-left"></span>
<button type="button" class="btn btn-success"><span id="workTime">25:00</span>
<button type="button" class="btn btn-success btn" id="increaseWork"> <span class="glyphicon glyphicon-menu-right"></span></div>
</div>
<br />
<br />
<br />
<br />
<div class="center">
<div class="boxed">
<br />
<span id="boxText">SESSION</span>
<br />
<br />
<br />
<span id="display"></span>
<br />
<span id="timerStatus"></span>
</div>
<br />
<button type="button" class="btn btn-success btn-sm" id="start">Start</button>
<button type="button" class="btn btn-success btn-sm" id="pause">Pause</button>
<button type="button" class="btn btn-success btn-sm" id="reset">Reset</button>
</div>
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'> </script>
<script src='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js'></script>
<script src="script.js"></script>
</body>
</html>
And the JavaScript:
var myInterval;
var workTime = document.getElementById("workTime").innerHTML = 25;
var breakTime = document.getElementById("breakTime").innerHTML = 5;
var remainSec = workTime * 60;
document.getElementById("display").innerHTML = workTime;
function startWork() {
document.getElementById("start").disabled = true;
timer(callback);
}
function pauseTime() {
clearInterval(myInterval);
document.getElementById("start").disabled = false;
}
function displayTime(remainingTime) {
if (remainingTime % 60 >= 10) {
document.getElementById('display').innerHTML = Math.floor(remainingTime / 60) + ':' + Math.floor(remainingTime % 60);
} else {
document.getElementById('display').innerHTML = Math.floor(remainingTime / 60) + ':' + "0" + Math.floor(remainingTime % 60);
}
}
function timer(pomodoro) {
var remainingTime = remainSec;
myInterval = setTimeout(function() {
displayTime(remainingTime);
if (remainingTime >= 0) {
remainSec--;
timer(pomodoro);
} else {
clearInterval();
pomodoro();
}
}, 1000);
}
var callback = function() {
console.log('callback');
document.getElementById('timerStatus').innerHTML = "Take a break!";
remainSec = breakTime * 60;
timer(callbackRest)
};
var callbackRest = function() {
clearInterval(myInterval);
console.log('callbackRest');
document.getElementById('timerStatus').innerHTML = "Begin";
remainSec = workTime * 60;
document.getElementById("start").disabled = false;
};
function resetTime() {
clearInterval(myInterval);
remainSec = workTime * 60;
startWork();
}
function decreaseWork() {
if (workTime >= 1) {
document.getElementById('workTime').innerHTML = --workTime;
remainSec = workTime * 60;
}
}
function decreaseBreak() {
if (breakTime >= 1) {
document.getElementById('breakTime').innerHTML = --breakTime;
}
}
function increaseWork() {
document.getElementById('workTime').innerHTML = ++workTime;
remainSec = workTime * 60;
}
function increaseBreak() {
document.getElementById('breakTime').innerHTML = ++breakTime;
}
document.getElementById('start').addEventListener('click', startWork);
document.getElementById('pause').addEventListener('click', pauseTime);
document.getElementById('reset').addEventListener('click', resetTime);
document.getElementById('decreaseWork').addEventListener('click', decreaseWork);
document.getElementById('decreaseBreak').addEventListener('click', decreaseBreak);
document.getElementById('increaseWork').addEventListener('click', increaseWork);
document.getElementById('increaseBreak').addEventListener('click', increaseBreak);
Any feedback is much appreciated!
I just added a few things.
First two flags were added to know if isPomodoroTime status and if isBreakTime status, maybe you ask why two? because I needed a initial state which is when both were false, with those flags I can incremente and display time without confusing, for that there is a new function callled changeTimeAndDisplay that is being called from all increase and decrease methods. I also put a startWork in the callback where suppose to be called when break time finish.
here is a demo - codepen.io
var myInterval;
var workTime = document.getElementById("workTime").innerHTML = 25;
var breakTime = document.getElementById("breakTime").innerHTML = 5;
var remainSec = workTime * 60;
var isPomodoroTime = false; //new
var isBreakTime = false; //new
//new function
function changeTimeAndDisplay(newTime){
remainSec = newTime * 60;
displayTime(remainSec);
}
document.getElementById("display").innerHTML = workTime;
function startWork() {
isPomodoroTime = true; //new
document.getElementById("start").disabled = true;
timer(callback);
}
function pauseTime() {
clearInterval(myInterval);
document.getElementById("start").disabled = false;
}
function displayTime(remainingTime) {
if (remainingTime % 60 >= 10) {
document.getElementById('display').innerHTML = Math.floor(remainingTime / 60) + ':' + Math.floor(remainingTime % 60);
} else {
document.getElementById('display').innerHTML = Math.floor(remainingTime / 60) + ':' + "0" + Math.floor(remainingTime % 60);
}
}
function timer(pomodoro) {
var remainingTime = remainSec;
myInterval = setTimeout(function() {
displayTime(remainingTime);
if (remainingTime >= 0) {
remainSec--;
timer(pomodoro);
} else {
clearInterval(myInterval); //new
pomodoro();
}
}, 1000);
}
var callback = function() {
isPomodoroTime = false; //new
isBreakTime = true; //new
console.log('callback');
document.getElementById('timerStatus').innerHTML = "Take a break!";
remainSec = breakTime * 60;
timer(callbackRest)
};
var callbackRest = function() {
isPomodoroTime = true; //new
isBreakTime = false; //new
clearInterval(myInterval);
console.log('callbackRest');
document.getElementById('timerStatus').innerHTML = "Begin";
remainSec = workTime * 60;
document.getElementById("start").disabled = false;
startWork(); //new
};
function resetTime() {
clearInterval(myInterval);
remainSec = workTime * 60;
startWork();
}
function decreaseWork() {
if (workTime >= 1) {
document.getElementById('workTime').innerHTML = --workTime;
if(isPomodoroTime || !isPomodoroTime && !isBreakTime){ //new if block
changeTimeAndDisplay(workTime);
}
}
}
function decreaseBreak() {
if (breakTime >= 1) {
document.getElementById('breakTime').innerHTML = --breakTime;
if(!isPomodoroTime && isBreakTime){ //new if block
changeTimeAndDisplay(breakTime);
}
}
}
function increaseWork() {
document.getElementById('workTime').innerHTML = ++workTime;
if(isPomodoroTime || !isPomodoroTime && !isBreakTime){ //new if block
changeTimeAndDisplay(workTime);
}
}
function increaseBreak() {
document.getElementById('breakTime').innerHTML = ++breakTime;
if(!isPomodoroTime && isBreakTime){ //new if block
changeTimeAndDisplay(breakTime);
}
}
document.getElementById('start').addEventListener('click', startWork);
document.getElementById('pause').addEventListener('click', pauseTime);
document.getElementById('reset').addEventListener('click', resetTime);
document.getElementById('decreaseWork').addEventListener('click', decreaseWork);
document.getElementById('decreaseBreak').addEventListener('click', decreaseBreak);
document.getElementById('increaseWork').addEventListener('click', increaseWork);
document.getElementById('increaseBreak').addEventListener('click', increaseBreak);
As advice you could simplify more your code for example make a function for document.getElementById(id).addEventListener(evnName,func);
function addAction(evnName,id,selector){
document.getElementById(id).addEventListener(evnName,func);
}
or
function addValue(id,value){
document.getElementById(id).innerHTML = value;
}
And replace all document.getElementById
regards.