HTML and Javascript Clicker Game Dollars per Second Not Working - javascript

My Dollars Per Second Counter Isn't Working. I have the right id in document.querySelector and the calculations are right. The Dollars per Second just isn't updating It seems the function is not running properly. I don't know what to do at all. I'm not getting any errors in the console either.
Click This Image
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="script.js"></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie#beta/dist/js.cookie.min.js"></script>
<link rel="stylesheet" href="style.css" />
<title>Computer Clicker</title>
</head>
<body onload="updateDollars()">
<div class="counterclass">
<h1 id="counter">0 dollars</h1>
<h3 id="dps">0.0 dps(Dollars per Second)</h3>
</div>
<div class="clickme">
<img
id="slightlydamagedcomputer"
onclick="clicker.dollars += clicker.clickMultiplier; var click = document.querySelector('.clickme'); click.style.animation = 'click 0.2s'; var clone = click.cloneNode(true); click.parentNode.replaceChild(clone, click);"
src="slightlydamagedcomputer.png"
alt="Drawing of a Smoking Computer"
width="500"
height="500"
/>
</div>
<div class="upgradesleft">
<h1>Upgrades</h1>
<div class="upgradeoptions">
<button></button>
<button></button>
<button></button>
<button></button>
<button></button>
</div>
</div>
<div class="genright">
<h1>Generators</h1>
<div class="genoptions"></div>
</div>
</body>
</html>
Javascript:
dollars: 0,
clickMultiplier: 1,
generators: {
cardboardMouse: {
amount: 0,
cost: 10,
dps: 0.5,
dollarsToShow: 5,
dollarsToUnlock: 10,
name: "Cardboard Mouse",
description:
"A poorly crafted cardboard version of a mouse. Need I say more?",
},
cardboardKeyboard: {
amount: 0,
cost: 50,
dps: 1,
dollarsToShow: 25,
dollarsToUnlock: 50,
name: "Cardboard Keyboard",
description:
"A poorly crafted cardboard version of a keyboard. Makes a satisfying noise.",
},
},
};
var delay = 0;
function thingClicked(thing) {
if (clicker.generators[thing].cost <= clicker.dollars) {
clicker.dollars -= clicker.generators[thing].cost;
clicker.generators[thing].amount++;
clicker.generators[thing].cost += Math.round(
clicker.generators[thing].cost * 0.15
);
updateGenerators();
/*updateDollarsPerSecond();*/
}
}
function dummyFunction() {
updateDollarsPerSecond();
}
function updateDollarsPerSecond(){
for (i in clicker.generators) {
dummyFunction();
console.log((clicker.generators[i].amount * clicker.generators[i].dps).toFixed(1) + " dps(Dollars per Second)")
document.querySelector("#dps").innerHTML = (clicker.generators[i].amount * clicker.generators[i].dps).toFixed(1) + " dps(Dollars per Second)";
}
}
function updateGenerators() {
document.querySelector(".genoptions").innerHTML = "";
for (i in clicker.generators) {
document.querySelector(
".genoptions"
).innerHTML += `<div><button onclick="thingClicked('${i}');"><h3>${clicker.generators[i].name}(${clicker.generators[i].amount})</h3><p>${clicker.generators[i].description}</p><p class="cost">$${clicker.generators[i].cost}</p><p class="dps">${clicker.generators[i].dps} dps</p></button></div>`;
}
}
function updateDollars() {
if (Cookies.get("clicker") != null && Cookies.get("clicker") != "undefined") {
var clicker1 = JSON.parse(Cookies.get("clicker"));
for (i in clicker.generators) {
if (clicker1.generators[i] == null) {
clicker1.generators[i] = clicker.generators[i];
}
}
clicker = clicker1;
}
updateGenerators();
setInterval(() => {
for (i in clicker.generators) {
clicker.dollars +=
(clicker.generators[i].amount * clicker.generators[i].dps) / 100;
}
if (clicker.dollars != 1) {
document.getElementById("counter").innerHTML =
String(clicker.dollars).split(".")[0] + " dollars";
} else {
document.getElementById("counter").innerHTML =
String(clicker.dollars).split(".")[0] + " dollar";
}
delay++;
if (delay >= 40) {
Cookies.set("clicker", JSON.stringify(clicker), { expires: 100000 });
delay = 0;
}
}, 10);
}
CSS:
#keyframes click {
50% {
transform: scale(0.95);
}
100% {
transform: scale(1);
}
}
body {
background-color: aquamarine;
}
h1,
#dps {
font-family: "Joan", serif;
}
#dps {
font-size: 15px;
}
#counter,
#dps {
text-align: center;
margin: 0px;
margin-top: 21.44px;
}
#slightlydamagedcomputer {
display: block;
margin: auto;
}
#slightlydamagedcomputer:hover {
cursor: pointer;
}
.upgradesleft {
left: 0px;
}
.genright {
right: 0px;
}
.upgradesleft,
.genright {
position: absolute;
top: 0px;
height: 100%;
}
.upgradesleft h1,
.genright h1 {
text-align: center;
}
.upgradeoptions button,
.genoptions button {
background-color: aliceblue;
border-style: solid;
border-color: black;
border-width: 1px;
height: 100px;
width: 400px;
display: block;
}
.upgradeoptions button {
border-radius: 0px 15px 15px 0px;
/*display: none;*/
}
.genoptions button {
border-radius: 15px 0px 0px 15px;
/*display: none;*/
}
.upgradeoptions div,
.genoptions div {
position: relative;
}
.cost {
left: 0px;
top: 0px;
border-radius: 15px;
}
.dps {
right: 0px;
top: 0px;
border-radius: 0px 0px 0px 15px;
}
.cost,
.dps {
background-color: lightgray;
border-style: solid;
border-color: black;
border-width: 1px;
position: absolute;
margin: 0px;
padding: 5px;
}

You are not updating the element with id dps. So you need to update it.
You need to modify your updateGenerators() function by adding the following lines:
document.querySelector("#dps").innerHTML = (clicker.generators[i].amount * clicker.generators[i].dps).toFixed(1) + " dps(Dollars per Second)";
and the updateGenerators() function will be:
function updateGenerators() {
document.querySelector(".genoptions").innerHTML = "";
for (i in clicker.generators) {
document.querySelector("#dps").innerHTML = (clicker.generators[i].amount * clicker.generators[i].dps).toFixed(1) + " dps(Dollars per Second)";
document.querySelector(
".genoptions"
).innerHTML += `<div><button onclick="thingClicked('${i}');"><h3>${clicker.generators[i].name}(${clicker.generators[i].amount})</h3><p>${clicker.generators[i].description}</p><p class="cost">$${clicker.generators[i].cost}</p><p class="dps">${clicker.generators[i].dps} dps</p></button></div>`;
}
}
Check the following modified js code:
var clicker = {
dollars: 0,
clickMultiplier: 1,
generators: {
cardboardMouse: {
amount: 0,
cost: 10,
dps: 0.5,
dollarsToShow: 5,
dollarsToUnlock: 10,
name: "Cardboard Mouse",
description: "A poorly crafted cardboard version of a mouse. Need I say more?",
},
cardboardKeyboard: {
amount: 0,
cost: 50,
dps: 1,
dollarsToShow: 25,
dollarsToUnlock: 50,
name: "Cardboard Keyboard",
description: "A poorly crafted cardboard version of a keyboard. Makes a satisfying noise.",
},
},
};
var delay = 0;
function thingClicked(thing) {
if (clicker.generators[thing].cost <= clicker.dollars) {
clicker.dollars -= clicker.generators[thing].cost;
clicker.generators[thing].amount++;
clicker.generators[thing].cost += Math.round(
clicker.generators[thing].cost * 0.15
);
updateGenerators();
/*updateDollarsPerSecond();*/
}
}
function dummyFunction() {
updateDollarsPerSecond();
}
function updateDollarsPerSecond() {
for (i in clicker.generators) {
dummyFunction();
console.log((clicker.generators[i].amount * clicker.generators[i].dps).toFixed(1) + " dps(Dollars per Second)")
document.querySelector("#dps").innerHTML = (clicker.generators[i].amount * clicker.generators[i].dps).toFixed(1) + " dps(Dollars per Second)";
}
}
function updateGenerators() {
document.querySelector(".genoptions").innerHTML = "";
for (i in clicker.generators) {
document.querySelector("#dps").innerHTML = (clicker.generators[i].amount * clicker.generators[i].dps).toFixed(1) + " dps(Dollars per Second)";
document.querySelector(
".genoptions"
).innerHTML += `<div><button onclick="thingClicked('${i}');"><h3>${clicker.generators[i].name}(${clicker.generators[i].amount})</h3><p>${clicker.generators[i].description}</p><p class="cost">$${clicker.generators[i].cost}</p><p class="dps">${clicker.generators[i].dps} dps</p></button></div>`;
}
}
function updateDollars() {
if (Cookies.get("clicker") != null && Cookies.get("clicker") != "undefined") {
var clicker1 = JSON.parse(Cookies.get("clicker"));
for (i in clicker.generators) {
if (clicker1.generators[i] == null) {
clicker1.generators[i] = clicker.generators[i];
}
}
clicker = clicker1;
}
updateGenerators();
setInterval(() => {
for (i in clicker.generators) {
clicker.dollars +=
(clicker.generators[i].amount * clicker.generators[i].dps) / 100;
}
if (clicker.dollars != 1) {
document.getElementById("counter").innerHTML =
String(clicker.dollars).split(".")[0] + " dollars";
} else {
document.getElementById("counter").innerHTML =
String(clicker.dollars).split(".")[0] + " dollar";
}
delay++;
if (delay >= 40) {
Cookies.set("clicker", JSON.stringify(clicker), {
expires: 100000
});
delay = 0;
}
}, 10);
}

Related

Javascript carosel animation

I'm trying to make an image carousel with center animation. I don't want to use CSS animations, instead I'd like to use jQuery.
By pressing the 'Prev' button the animation will start. One of the slides which will be central begins to grow. I've used jQuery's animate() to animate width and height. Everything works as required except I can't understand why the animation makes the central slide jump.
I have created this sample. If you push the 'Prev' button the animation will start.
var scroll_speed = 4000;
var items_cnt = $('.mg_item').length;
var container_size = $(".main_cnt").innerWidth();
var item_avg_w = container_size / 5;
var item_center_w = ((item_avg_w / 100) * 20) + item_avg_w;
var item_center_h = (item_center_w / 16) * 9 + 30;
var item_w = ((container_size - item_center_w) / 4) - 2;
var item_h = ((item_w / 16) * 9);
var gallery_content = $('.gallery_body').html();
$('.gallery_body').html(gallery_content + gallery_content + gallery_content);
var items_offset = items_cnt * item_w + 14;
$('.gallery_body').css('left', -items_offset);
$('.mg_item').css("width", item_w);
$('.mg_item').css("height", item_h);
//$('.mg_item').css("margin-bottom", (item_center_h - item_h) / 2);
//$('.mg_item').css("margin-top", (item_center_h - item_h) / 2);
//$('.mg_item_с').css("width", item_center_w);
//$('.mg_item_с').css("height", item_center_h);
//document.documentElement.style.setProperty('--center_width', item_center_w + "px");
//document.documentElement.style.setProperty('--center_height', item_center_h + "px");
$('.main_cnt').css("height", item_center_h);
check_visible();
AssignCenter(0);
function gonext() {
AssignCenter(-1);
ZoomIn();
$('.gallery_body').animate({
left: '+=' + (item_w + 2),
}, scroll_speed, "linear", function() {
LoopSlides();
});
}
function goprev() {
AssignCenter(1);
ZoomIn();
$('.gallery_body').animate({
left: '-=' + (item_w + 2),
}, scroll_speed, "linear", function() {
LoopSlides();
});
}
function ZoomIn() {
$('.center').animate({
width: item_center_w + 'px',
height: item_center_h + 'px',
}, scroll_speed, function() {});
}
function LoopSlides() {
var cur_pos = $('.gallery_body').position().left
var left_margin = Math.abs(items_offset * 2 - item_w) * -1;
var right_margin = 0 - item_w;
if (cur_pos < left_margin) {
$('.gallery_body').css('left', -items_offset);
}
if (cur_pos >= 0) {
$('.gallery_body').css('left', -items_offset);
}
check_visible();
AssignCenter(0);
}
function check_visible() {
$('.mg_item').each(function(i, obj) {
var pos = $(this).offset().left;
if (pos < 0 || pos > container_size) {
$(this).addClass("invisible");
$(this).removeClass("active");
} else {
$(this).addClass("active");
$(this).removeClass("invisible");
}
});
}
function AssignCenter(offset) {
var center_slide = $('.active')[2 + offset];
$('.center').each(function(i, obj) {
$(this).removeClass("center");
});
$(center_slide).addClass("center");
//$(center_slide).css("width", item_center_w);
//$(center_slide).css("height", item_center_h);
}
:root {
--center_width: 0px;
--center_height: 0px;
}
.main_cnt {
background-color: rgb(255, 0, 0);
padding: 0px;
overflow: hidden;
margin: 0px;
}
.gallery_body {
width: 500%;
background-color: rgb(128, 128, 128);
position: relative;
}
.mg_item {
width: 198px;
height: 150px;
background-color: blue;
display: inline-block;
position: relative;
margin: -1px;
padding: 0px;
font-size: 120px;
}
.center {
background-color: brown;
/*width: var(--center_width) !important;
height: var(--center_height) !important;*/
}
.item_c {
width: 410px;
height: 150px;
background-color: blueviolet;
display: inline-block;
position: relative;
margin: -1px;
padding: 0px;
font-size: 120px;
}
.video-js .vjs-dock-text {
text-align: right;
}
<script src="https://code.jquery.com/jquery-2.2.0.min.js" type="text/javascript"></script>
<div class="main_cnt">
<div class="gallery_body">
<div class="mg_item">1</div>
<div class="mg_item">2</div>
<div class="mg_item">3</div>
<div class="mg_item">4</div>
<div class="mg_item">5</div>
<div class="mg_item">6</div>
<div class="mg_item">7</div>
</div>
</div>
<br><br>
<button onclick="gonext()">GONEXT</button>
<button onclick="goprev()">GOPREV</button>
<button onclick="check_visible()">CHEVIS</button>

JavaScript InnerHTML not updating

This is a typing game that I am working on. I am pretty much done with it except for one problem that I am having. When the person finishes typing all of the words in the turboTypingArray, I call my gameWin() function which assigns the class game-over-win to the div with the id "board" and edits the innerHTML of "board". However, it is only adding the class but not the innerHTML. How can I fix this? I apologize in advance if my code is difficult to understand, I am new o this and still learning.
//CONSTANTS
let duplicate;
const easyWords = ["dog", "cat", "bat", "axe", "hat", "ant", "sat", "rug", "mug", "bet", "art", "can", "day", "box", "egg", "few", "bed", "job", "hot", "men", "use", "sun", "jar", "lip", "flu", "aim", "red", "lid", "ear", "tea", "ski", "oak", "gum", "ham", "mob", "nut", "shy", "van", "elk", "gem", "rap", "fur", "eve", "cry", "mad", "ore", "tax", "six", "pet", "old", "map", "gym", "leg", "bus", "app", "war", "yes", "mud", "rim", "duo"];
const mediumWords = ["house", "beach", "adult", "chief", "funny", "hello", "metal", "sauce", "cocoa", "flags", "upset", "pearl", "trash", "enemy", "pizza", "humor", "eagle", "flame", "cargo", "puppy", "retro", "spark", "bride", "straw", "inbox", "bored", "chalk", "fatal", "hobby", "melee", "bagel", "debug", "amaze", "witch", "stool", "thief", "acorn", "hover", "lever", "merge", "lunar", "debit", "cubic", "erase", "vivid", "waist", "yeast", "syrup", "trunk", "rebel", "lobby", "pasta", "grape", "choir", "jewel", "scoop", "rival", "yacht", "sushi", "bunny"];
const hardWords = ["ability", "battery", "compare", "illness", "weather", "speaker", "package", "organic", "quickly", "regular", "premium", "musical", "journal", "healthy", "economy", "connect", "gallery", "illegal", "parking", "roughly", "success", "accused", "chronic", "unusual", "version", "setting", "message", "removal", "several", "dispute", "tourist", "avocado", "witness", "soldier", "monster", "habitat", "crystal", "younger", "analyze", "nervous", "precise", "trailer", "satisfy", "minimal", "fortune", "genuine", "bizarre", "exhibit", "gesture", "nucleus", "pivotal", "rainbow", "mustard", "lottery", "address", "network", "legally", "cartoon", "horizon", "induced"];
for (var i = 0; i < hardWords.length; i++) {
for (var j = i+1; j < hardWords.length; j++) {
if (hardWords[i] == hardWords[j]) {
duplicate = hardWords[j]
console.log(duplicate)
}
}
}
//VARIABLES
let turboTypingArray = [];
let word
let score = 0;
let attempts = 0;
let correctAttempts = 0;
let answerStreak = 0;
let highestAnswerStreak = 0;
let timeRemaining;
let myTimer;
//EVENT LISTENERS
var input = document.getElementById("user-input");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("input-word").click();
};
});
document.getElementById("easy").onclick = setEasy;
document.getElementById("medium").onclick = setMedium;
document.getElementById("hard").onclick = setHard;
//FUNCTIONS
function init() {
score = 0;
attempts = 0;
correctAttempts = 0;
answerStreak = 0;
highestAnswerStreak = 0;
timeRemaining = 120;
clearInterval(myTimer);
document.getElementById("timer").innerHTML = "2:00";
myTimer = setInterval(updateTimer, 1000);
if (document.getElementById("board").classList.contains("game-over-lose")) {
document.getElementById("board").classList.remove("game-over-lose");
}
if (document.getElementById("board").classList.contains("game-over-win")) {
document.getElementById("board").classList.remove("game-over-win");
}
}
function refresh() {
var newWordBoard = "";
turboTypingArray.forEach((item, i) => {
newWordBoard += "<div class='board-word'>" +item + "</div>"
});
document.getElementById("board").innerHTML = newWordBoard;
}
function setEasy() {
init();
turboTypingArray = easyWords.slice();
document.getElementById("user-input").focus();
refresh();
}
function setMedium() {
init();
turboTypingArray = mediumWords.slice();
turboTypingArray.forEach((item, i) => {
document.getElementById("board").innerHTML += "<div class='board-word'>" +item + "</div>"
});
document.getElementById("user-input").focus();
refresh();
}
function setHard() {
init();
turboTypingArray = hardWords.slice();
turboTypingArray.forEach((item, i) => {
document.getElementById("board").innerHTML += "<div class='board-word'>" +item + "</div>"
});
document.getElementById("user-input").focus();
refresh();
}
function CheckInput() {
word = document.getElementById("user-input").value;
if (turboTypingArray.includes(word)) {
correctWord()
}
else {
wrongWord();
}
document.getElementById("user-input").value = "";
refresh();
}
function correctWord() {
answerStreak = answerStreak + 1;
if (answerStreak > highestAnswerStreak) {
highestAnswerStreak = answerStreak
}
score = score + 10 + answerStreak;
attempts = attempts + 1;
correctAttempts = correctAttempts + 1;
for (var i = 0; i < turboTypingArray.length; i++) {
if(turboTypingArray[i] == word) {
turboTypingArray.splice(i, 1);
}
}
checkDone();
}
function wrongWord() {
attempts = attempts + 1;
answerStreak = 0;
alert("das wrong broke boi")
}
function checkDone() {
if (turboTypingArray.length < 1) {
score = score - (attempts - correctAttempts);
alert("kfdskn")
clearInterval(myTimer);
gameWin();
}
}
function gameOver() {
document.getElementById("board").classList.add("game-over-lose");
document.getElementById("board").innerHTML = "Score: " + score + "<br>Attempts: " + attempts + "<br>Correct Attempts: " + correctAttempts + "<br>Highest Answer Streak: " + highestAnswerStreak + "<br>Words Remaining: " + turboTypingArray.length + "/60";
}
function gameWin() {
console.log("win");
document.getElementById("board").classList.add("game-over-win");
document.getElementById("board").innerHTML = "Score: " + score + "<br>Attempts: " + attempts + "<br>Correct Attempts: " + correctAttempts + "<br>Highest Answer Streak: " + highestAnswerStreak + "<br>Words Remaining: " + turboTypingArray.length + "/60";
}
function updateTimer() {
timeRemaining--
if (timeRemaining > 60) {
timerSeconds = timeRemaining - 60;
timerDisplay = "1:" + timerSeconds;
}
if (timeRemaining < 70) {
timerSeconds = timeRemaining - 60
timerDisplay = "1:0" + timerSeconds;
}
if (timeRemaining < 60) {
timerDisplay = "0:" + timeRemaining;
}
if (timeRemaining < 10) {
timerDisplay = "0:0" + timeRemaining;
}
if (timeRemaining < 1) {
gameOver();
clearInterval(myTimer);
}
document.getElementById("timer").innerHTML = timerDisplay;
}
body {
text-align: center;
font-family: "Roboto", monospace;
color: white;
background-color: black;
}
h1 {
margin: 0 auto;
font-family: "Major Mono Display", monospace;
font-size: 48px;
margin: 2%;
}
input {
border-radius: 25px;
height: 50px;
width: 400px;
font-family: "Major Mono Display", monospace;
margin: auto;
font-size: 37px;
text-align: center;
}
button {
background-color: black;
color: white;
height: 50px;
width: 160px;
font-size: 37px;
}
.difficulty-level {
width: 100px;
padding: 3px 0;
margin: auto;;
margin-top: 5px;
margin-bottom: 5px;
text-align: center;
color: black;
}
.board {
height: 220px;
width: 60px;
margin-bottom: 10px;
}
.board-word {
border: 1px solid white;
height: 40px;
width: 130px;
margin: auto;
text-align: center;
font-size: 30px;
}
.user-input {
margin-top: 10px;
}
.container {
display: flex;
justify-content: center;
align-items: center;
}
.wrap {
flex-wrap: wrap;
height: 400px;
width: 1400px;
}
.game-over-lose {
background-color: rgb(255, 0, 0, 0.2);
font-size: 40px;
color: white;
}
.game-over-win {
background-color: lightgreen;
font-size: 40px;
color: white;
}
#difficulty {
margin-bottom: 10px;
margin: auto;
font-family: "Major Mono Display", monospace;
}
#easy {
color: lightgreen;
border: 1px solid lightgreen;
}
#medium {
color: yellow;
border: 1px solid yellow;
}
#hard {
color: red;
border: 1px solid red;
}
#board {
margin: auto;
}
#font-face {
font-family: "digital-clock";
src: url("../fonts/digital-7.ttf");
}
#timer {
font-size: 80px;
font-family: "digital-clock"
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link href="https://fonts.googleapis.com/css?family=Major+Mono+Display" rel="stylesheet" />
<link href="css/styles.css" rel="stylesheet" type="text/css" />
<script defer src="js/app.js"></script>
<title>Turbo Typing</title>
</head>
<body>
<h1>turbo typing</h1>
<h2>Select a Difficulty</h2>
<div id="difficulty" class="">
<div id="easy" class="difficulty-level" >easy</div>
<div id="medium" class="difficulty-level">medium</div>
<div id="hard" class="difficulty-level">hard</div>
</div>
<div id="timer"></div>
<div id="board" class="wrap container">
</div>
<div class='user-input'>
<input id = "user-input" type = "text" value = "" />
<button id="input-word" onclick="CheckInput()">Enter</button>
</div>
</body>
</html>
Must say, it was really hard to find the issue :D.
You are calling refresh() on every input check, it also gets called either on a gameOver() or gameWin(). I have set a flag, gameDone, if its true, I do not refresh. I set gameDone to true on gameWin() or gameOver() and reset it back in a refresh.
To test it out, select the "EASY" level and just enter "DOG".
//CONSTANTS
let duplicate;
const easyWords = ["dog"];
const mediumWords = ["house", "beach", "adult", "chief", "funny", "hello", "metal", "sauce", "cocoa", "flags", "upset", "pearl", "trash", "enemy", "pizza", "humor", "eagle", "flame", "cargo", "puppy", "retro", "spark", "bride", "straw", "inbox", "bored", "chalk", "fatal", "hobby", "melee", "bagel", "debug", "amaze", "witch", "stool", "thief", "acorn", "hover", "lever", "merge", "lunar", "debit", "cubic", "erase", "vivid", "waist", "yeast", "syrup", "trunk", "rebel", "lobby", "pasta", "grape", "choir", "jewel", "scoop", "rival", "yacht", "sushi", "bunny"];
const hardWords = ["ability", "battery", "compare", "illness", "weather", "speaker", "package", "organic", "quickly", "regular", "premium", "musical", "journal", "healthy", "economy", "connect", "gallery", "illegal", "parking", "roughly", "success", "accused", "chronic", "unusual", "version", "setting", "message", "removal", "several", "dispute", "tourist", "avocado", "witness", "soldier", "monster", "habitat", "crystal", "younger", "analyze", "nervous", "precise", "trailer", "satisfy", "minimal", "fortune", "genuine", "bizarre", "exhibit", "gesture", "nucleus", "pivotal", "rainbow", "mustard", "lottery", "address", "network", "legally", "cartoon", "horizon", "induced"];
for (var i = 0; i < hardWords.length; i++) {
for (var j = i+1; j < hardWords.length; j++) {
if (hardWords[i] == hardWords[j]) {
duplicate = hardWords[j]
console.log(duplicate)
}
}
}
//VARIABLES
let turboTypingArray = [];
let word
let score = 0;
let attempts = 0;
let correctAttempts = 0;
let answerStreak = 0;
let highestAnswerStreak = 0;
let timeRemaining;
let myTimer;
let gameDone = false;
//EVENT LISTENERS
var input = document.getElementById("user-input");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("input-word").click();
};
});
document.getElementById("easy").onclick = setEasy;
document.getElementById("medium").onclick = setMedium;
document.getElementById("hard").onclick = setHard;
//FUNCTIONS
function init() {
score = 0;
attempts = 0;
correctAttempts = 0;
answerStreak = 0;
highestAnswerStreak = 0;
timeRemaining = 120;
clearInterval(myTimer);
document.getElementById("timer").innerHTML = "2:00";
myTimer = setInterval(updateTimer, 1000);
if (document.getElementById("board").classList.contains("game-over-lose")) {
document.getElementById("board").classList.remove("game-over-lose");
}
if (document.getElementById("board").classList.contains("game-over-win")) {
document.getElementById("board").classList.remove("game-over-win");
}
}
function refresh() {
gameDone = false;
var newWordBoard = "";
turboTypingArray.forEach((item, i) => {
newWordBoard += "<div class='board-word'>" +item + "</div>"
});
document.getElementById("board").innerHTML = newWordBoard;
}
function setEasy() {
init();
turboTypingArray = easyWords.slice();
document.getElementById("user-input").focus();
refresh();
}
function setMedium() {
init();
turboTypingArray = mediumWords.slice();
turboTypingArray.forEach((item, i) => {
document.getElementById("board").innerHTML += "<div class='board-word'>" +item + "</div>"
});
document.getElementById("user-input").focus();
refresh();
}
function setHard() {
init();
turboTypingArray = hardWords.slice();
turboTypingArray.forEach((item, i) => {
document.getElementById("board").innerHTML += "<div class='board-word'>" +item + "</div>"
});
document.getElementById("user-input").focus();
refresh();
}
function CheckInput() {
word = document.getElementById("user-input").value;
if (turboTypingArray.includes(word)) {
correctWord()
}
else {
wrongWord();
}
document.getElementById("user-input").value = "";
if (gameDone === false) {
refresh();
}
}
function correctWord() {
answerStreak = answerStreak + 1;
if (answerStreak > highestAnswerStreak) {
highestAnswerStreak = answerStreak
}
score = score + 10 + answerStreak;
attempts = attempts + 1;
correctAttempts = correctAttempts + 1;
for (var i = 0; i < turboTypingArray.length; i++) {
if(turboTypingArray[i] == word) {
turboTypingArray.splice(i, 1);
}
}
checkDone();
}
function wrongWord() {
attempts = attempts + 1;
answerStreak = 0;
alert("das wrong broke boi")
}
function checkDone() {
if (turboTypingArray.length < 1) {
score = score - (attempts - correctAttempts);
alert("kfdskn")
clearInterval(myTimer);
gameWin();
}
}
function gameOver() {
document.getElementById("board").classList.add("game-over-lose");
document.getElementById("board").innerHTML = "Score: " + score + "<br>Attempts: " + attempts + "<br>Correct Attempts: " + correctAttempts + "<br>Highest Answer Streak: " + highestAnswerStreak + "<br>Words Remaining: " + turboTypingArray.length + "/60";
gameDone = true;
}
function gameWin() {
console.log("win");
document.getElementById("board").classList.add("game-over-win");
document.getElementById("board").innerHTML = "Score: " + score + "<br>Attempts: " + attempts + "<br>Correct Attempts: " + correctAttempts + "<br>Highest Answer Streak: " + highestAnswerStreak + "<br>Words Remaining: " + turboTypingArray.length + "/60";
gameDone = true;
}
function updateTimer() {
timeRemaining--
if (timeRemaining > 60) {
timerSeconds = timeRemaining - 60;
timerDisplay = "1:" + timerSeconds;
}
if (timeRemaining < 70) {
timerSeconds = timeRemaining - 60
timerDisplay = "1:0" + timerSeconds;
}
if (timeRemaining < 60) {
timerDisplay = "0:" + timeRemaining;
}
if (timeRemaining < 10) {
timerDisplay = "0:0" + timeRemaining;
}
if (timeRemaining < 1) {
gameOver();
clearInterval(myTimer);
}
document.getElementById("timer").innerHTML = timerDisplay;
}
body {
text-align: center;
font-family: "Roboto", monospace;
color: white;
background-color: black;
}
h1 {
margin: 0 auto;
font-family: "Major Mono Display", monospace;
font-size: 48px;
margin: 2%;
}
input {
border-radius: 25px;
height: 50px;
width: 400px;
font-family: "Major Mono Display", monospace;
margin: auto;
font-size: 37px;
text-align: center;
}
button {
background-color: black;
color: white;
height: 50px;
width: 160px;
font-size: 37px;
}
.difficulty-level {
width: 100px;
padding: 3px 0;
margin: auto;;
margin-top: 5px;
margin-bottom: 5px;
text-align: center;
color: black;
}
.board {
height: 220px;
width: 60px;
margin-bottom: 10px;
}
.board-word {
border: 1px solid white;
height: 40px;
width: 130px;
margin: auto;
text-align: center;
font-size: 30px;
}
.user-input {
margin-top: 10px;
}
.container {
display: flex;
justify-content: center;
align-items: center;
}
.wrap {
flex-wrap: wrap;
height: 400px;
width: 1400px;
}
.game-over-lose {
background-color: rgb(255, 0, 0, 0.2);
font-size: 40px;
color: white;
}
.game-over-win {
background-color: lightgreen;
font-size: 40px;
color: white;
}
#difficulty {
margin-bottom: 10px;
margin: auto;
font-family: "Major Mono Display", monospace;
}
#easy {
color: lightgreen;
border: 1px solid lightgreen;
}
#medium {
color: yellow;
border: 1px solid yellow;
}
#hard {
color: red;
border: 1px solid red;
}
#board {
margin: auto;
}
#font-face {
font-family: "digital-clock";
src: url("../fonts/digital-7.ttf");
}
#timer {
font-size: 80px;
font-family: "digital-clock"
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link href="https://fonts.googleapis.com/css?family=Major+Mono+Display" rel="stylesheet" />
<link href="css/styles.css" rel="stylesheet" type="text/css" />
<script defer src="js/app.js"></script>
<title>Turbo Typing</title>
</head>
<body>
<h1>turbo typing</h1>
<h2>Select a Difficulty</h2>
<div id="difficulty" class="">
<div id="easy" class="difficulty-level" >easy</div>
<div id="medium" class="difficulty-level">medium</div>
<div id="hard" class="difficulty-level">hard</div>
</div>
<div id="timer"></div>
<div id="board" class="wrap container">
</div>
<div class='user-input'>
<input id = "user-input" type = "text" value = "" />
<button id="input-word" onclick="CheckInput()">Enter</button>
</div>
</body>
</html>

why the button will only change the object properties after the input is manually changed?

Attached is full code of the application.
The problem is that the buttons of the session length section will only change the CLOCK.session properties and the #countdown span if the session length input is changed first. What is strange is that this code worked before I started to do CSS styling to the page, but no it doesn't (and there should't be any connection).
Thank you for the help!`
const canvas = document.querySelector('#timer-circle');
const context = canvas.getContext('2d');
const CLOCK = {
timerInit: function() {
context.beginPath();
context.strokeStyle = "#527A71";
context.lineWidth = 2;
context.arc(120, 120, 118, 0, 2 * Math.PI);
context.stroke();
},
drawStep: function() {
context.beginPath();
context.lineWidth = 4;
context.fillStyle = "#505000";
context.arc(120, 120, 115, Math.PI / 2 - Math.PI * CLOCK.whichSession().timeStep, Math.PI / 2 + Math.PI * CLOCK.whichSession().timeStep);
context.stroke();
context.fill();
document.querySelector('#countdown').innerText = Math.floor(CLOCK.whichSession().timeZero / 60).toString() + ':' + (CLOCK.whichSession().timeZero % 60).toString();
},
initCount: function(total) {
total *= 60
if(CLOCK.sessionSwitch) {
CLOCK.session.timeZero = total;
let localTimeZero = total;
CLOCK.session.timeStep = (total - localTimeZero) / total;
}
else if(!CLOCK.sessionSwitch) {
CLOCK.breakProp.timeZero = total;
let localTimeZero = total;
CLOCK.breakProp.timeStep = (total - localTimeZero) / total;
}
},
clockDisplay: function(total, zero) {
document.querySelector('#countdown').innerText = total.toString() + ':00';
},
timerReset: function() {
context.clearRect(0, 0, canvas.width, canvas.height);
//INITIALIZING FUNCTIONS AND BUTTONS
},
whichSession: function() {
return CLOCK.sessionSwitch ? CLOCK.session : CLOCK.breakProp;
},
timerCount: function() {
if(CLOCK.whichSession().timeStep <= 1) {
CLOCK.drawStep();
CLOCK.whichSession().timeZero--;
CLOCK.whichSession().timeStep = (60 * CLOCK.whichSession().timeTotal - CLOCK.whichSession().timeZero) / (60 * CLOCK.whichSession().timeTotal);
}
else if(CLOCK.whichSession().timeStep >= 1) {
if(CLOCK.sessionSwitch) {
// INITIALIZING BREAK COUNT
CLOCK.sessionSwitch = false;
document.querySelector('#label').innerText = 'Break!';
CLOCK.timerReset();
CLOCK.timerInit();
CLOCK.initCount(CLOCK.breakProp.timeTotal);
}
else if(!CLOCK.sessionSwitch) {
// INITIALIZING SESSION COUNT
CLOCK.sessionSwitch = true;
document.querySelector('#label').innerText = 'Session';
CLOCK.timerReset();
CLOCK.timerInit();
CLOCK.initCount(CLOCK.session.timeTotal);
}
//reset the circle
//switch the countdown to the correct time
CLOCK.drawStep();
CLOCK.whichSession().timeZero--;
CLOCK.whichSession().timeStep = (60 * CLOCK.whichSession().timeTotal - CLOCK.whichSession().timeZero) / (60 * CLOCK.whichSession().timeTotal);
}
},
timerSwitch: false,
sessionSwitch: true,
session: {
timeTotal: undefined,
timeZero: undefined,
timeStep: undefined
},
breakProp: {
timeTotal: undefined,
timeZero: undefined,
timeStep: undefined
},
timerInterval: undefined,
};
$(document).ready(function() {
CLOCK.timerInit()
CLOCK.clockDisplay(document.querySelector('#session-length input').value);
CLOCK.session.timeTotal = Number(document.querySelector('#session-length input').value)
CLOCK.breakProp.timeTotal = Number(document.querySelector('#break-length input').value)
$('button.increase').click(function() {
if($(this)['0'].nextElementSibling.value >= 1 && $(this)['0'].nextElementSibling.value < 99) {
if(this.parentNode.id == 'session-length') {
$(this)['0'].nextElementSibling.value++;
CLOCK.session.timeTotal++;
CLOCK.clockDisplay($(this)[0].nextElementSibling.value);
}
else if(this.parentNode.id = 'break-length') {
$(this)['0'].nextElementSibling.value++;
CLOCK.breakProp.timeTotal++;
}
}
});
$('button.decrease').click(function() {
if($(this)['0'].previousElementSibling.value > 1 && $(this)['0'].previousElementSibling.value <= 99) {
$(this)['0'].previousElementSibling.value--;
if(this.parentNode.id == 'session-length') {
CLOCK.session.timeTotal--;
CLOCK.clockDisplay($(this)[0].previousElementSibling.value);
}
else if(this.parentNode.id = 'break-length') {
CLOCK.breakProp.timeTotal--;
}
}
});
$('input').on('keyup', function() {
if(this.parentNode.id = 'session-length') {
CLOCK.session.timeTotal = Number(this.value);
CLOCK.clockDisplay(this.value);
}
else if(this.parentNode.id = 'break-length') {
CLOCK.breakProp.timeTotal = Number(this.value);
}
});
$('#timer-count').on('click', function() {
if(!CLOCK.timerSwitch) {
CLOCK.initCount(CLOCK.session.timeTotal);
CLOCK.timerInterval = setInterval(CLOCK.timerCount, 1000);
CLOCK.timerSwitch = true;
$('button, input').prop('disabled', true);
}
else if(CLOCK.timerSwitch) {
clearInterval(CLOCK.timerInterval);
CLOCK.timerSwitch = false;
CLOCK.sessionSwitch = true;
CLOCK.clockDisplay(CLOCK.session.timeTotal, )
CLOCK.timerReset();
CLOCK.timerInit();
$('button, input').prop('disabled', false);
}
});
});
body {
background: rgb(0, 0, 0);
background: -moz-linear-gradient(-45deg, rgba(0, 0, 0, 1) 0%, rgba(38, 36, 0, 1) 51%, rgba(81, 66, 0, 1) 100%);
background: -webkit-linear-gradient(-45deg, rgba(0, 0, 0, 1) 0%, rgba(38, 36, 0, 1) 51%, rgba(81, 66, 0, 1) 100%);
background: linear-gradient(135deg, rgba(0, 0, 0, 1) 0%, rgba(38, 36, 0, 1) 51%, rgba(81, 66, 0, 1) 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#000000', endColorstr='#514200', GradientType=1);
background-repeat: no-repeat;
background-attachment: fixed;
color: white;
}
#clock-container {
margin: 100px 20% 0 35%;
color: white;
}
input {
width: 65px;
background-color: transparent;
color: inherit;
border: solid 7px green;
border-radius: 20px;
text-align: center;
font-weight: 700;
font-size: 2em;
}
.input {
display: inline-block;
margin-right: 10%;
}
.clock-form {
display: flex;
padding: 0 5%;
}
.decrease {
margin-left: 0px;
}
#animation {
margin-top: 50px;
margin-left: 7%;
}
#timer-count {
position: absolute;
text-align: center;
width: 240px;
height: 240px;
z-index: 2;
padding: 80px 20px;
font-size: 25px;
font-weight: 600;
}
#timer-circle {
position: absolute;
z-index: 1;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Alon's Pomodoro Clock</title>
<!-- =========JQUERY -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- ==============>BOOTSTRAP -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<!-- ============>FONT -->
<link href="https://fonts.googleapis.com/css?family=Gochi+Hand" rel="stylesheet">
<!-- ================>STYLESHEET -->
<link rel="stylesheet" href="stylesheet.css">
</head>
<body>
<div id="clock-container">
<h1>Alon's Pomodoro Clock</h1>
<div id="session-length" class="input">
<h3>Session Length</h3>
<div class="clock-form">
<button class="increase">+</button>
<input type="text" maxlength="2" value="25" />
<button class="decrease">-</button>
</div>
</div>
<div id="break-length" class="input">
<h3>Break Length</h3>
<div class="clock-form">
<button class="increase">+</button>
<input type="text" maxlength="2" value="5" />
<button class="decrease">-</button>
</div>
</div>
<div id="animation">
<canvas id="timer-circle" width="240" height="240">
</canvas>
<div id="timer-count">
<span id="label">Session</span>
<span id="countdown">01:00</span>
</div>
</div>
</div>
<script src="javascript.js"></script>
</body>
</html>
`
SOLVED!
problem was that I added a div with class .clock-form while editing the css, therefore $(this)['0'].parentNode.id refered to .clock-form instead of either session-input or break-input. though I still haven't figured out why the buttons worked after inserting a value to the inputs manually.

Add/remove box in html using angularJS

I want to create/use an add-remove box like this in HTML using angularJS where you have a list of some objects on the left and you select the objects to put them on under the headings listed on the right. Any idea what do we call such tables/lists and can I create/find them?
I don't know what is the accurate title to call it :)
but I tried to implement a sample of 'add/remove box' to achieve the concept you want with AngularJS!
the main part consists of three sections:
left section which is going to be added
middle section which contains the buttons
right section which is going to be removed
The code below applies the above section which aforesaid:
<div class="box leftBox">
<div>
<div id="{{left.name}}" ng-click="clicked($event, 0)" data-ng-repeat="left in lefts">{{left.name}}</div>
</div>
</div>
<div class="box button_holder">
<button ng-click="add()" class="button button-blue">ADD ></button>
<button ng-click="remove()" class="button button-red">< REMOVE</button>
<button ng-click="addAll()" class="button button-blue button-dark">ADD ALL >></button>
<button ng-click="removeAll()" class="button button-red button-dark"><< REMOVE ALL</button>
<button ng-click="deleteChoice()" class="button delete">X</button>
</div>
<div class="box rightBox">
<div>
<div ng-click="clicked($event, 1)" data-ng-repeat="right in rights">{{right.name}}</div>
</div>
</div>
by using angularjs directives including data-ng-repeat you can control the procedure of adding or removing
here is the implemented overview.
here is the completed code on the "codepen".
you can also check my github.
try to run the snippet in a fullscreen window!
/**
* Created by ALIREZA on 8/30/2017.
*/
var app = angular.module('Add_Remove_Box', []);
app.controller('Ctrl', function($scope) {
var i;
var isRepeated = false;
var actionLicense = true;
var prevElement = null;
var currentElement = null;
var positionSide = null;
$scope.choices = ["left", "right"];
$scope.lefts = [{
id: 'left1'
}, {
id: 'left2'
}, {
id: 'left3'
}, {
id: 'left4'
}];
for (i = 0; i < $scope.lefts.length; i++) {
$scope.lefts[i].name = "left" + (i + 1).toString();
}
$scope.rights = [{
id: 'right1'
}, {
id: 'right2'
}];
for (i = 0; i < $scope.rights.length; i++) {
$scope.rights[i].name = "right" + (i + 1).toString();
}
$scope.insert = function($event) {
var side = $scope.selectedSide;
if (side == null || side == "left") {
var leftItemNo = $scope.lefts.length + 1;
$scope.lefts.push({
'id': 'left' + leftItemNo
});
$scope.lefts[leftItemNo - 1].name = $scope.choice.name;
} else {
var rightItemNo = $scope.rights.length + 1;
$scope.rights.push({
'id': 'right' + rightItemNo
});
$scope.rights[rightItemNo - 1].name = $scope.choice.name;
}
};
$scope.deleteChoice = function() {
if (positionSide === 0) {
var ItemNo = -1;
$scope.lefts.forEach(function(i, j) {
if (i.name === currentElement.textContent) {
ItemNo = j;
return;
}
});
$scope.lefts.splice(ItemNo, 1);
}
};
$scope.add = function() {
if (actionLicense && positionSide === 0) {
actionLicense = false;
var leftItemNo = -1;
$scope.lefts.forEach(function(i, j) {
if (i.name === currentElement.textContent) {
leftItemNo = j;
return;
}
});
$scope.lefts.splice(leftItemNo, 1);
var rightItemNo = $scope.rights.length + 1;
$scope.rights.push({
'id': 'right' + rightItemNo
});
$scope.rights[rightItemNo - 1].name = currentElement.textContent;
}
};
$scope.remove = function() {
if (actionLicense && positionSide === 1) {
actionLicense = false;
var rightItemNo = -1;
$scope.rights.forEach(function(i, j) {
if (i.name === currentElement.textContent) {
rightItemNo = j;
return;
}
});
$scope.rights.splice(rightItemNo, 1);
var leftItemNo = $scope.lefts.length + 1;
$scope.lefts.push({
'id': 'left' + leftItemNo
});
$scope.lefts[leftItemNo - 1].name = currentElement.textContent;
}
};
$scope.addAll = function() {
$scope.lefts.forEach(function(i) {
var rightItemNo = $scope.rights.length + 1;
$scope.rights.push({
'id': 'right' + rightItemNo
});
$scope.rights[rightItemNo - 1].name = i.name;
});
$scope.lefts.splice(0, $scope.lefts.length);
};
$scope.removeAll = function() {
$scope.rights.forEach(function(i) {
var leftItemNo = $scope.lefts.length + 1;
$scope.lefts.push({
'id': 'left' + leftItemNo
});
$scope.lefts[leftItemNo - 1].name = i.name;
});
$scope.rights.splice(0, $scope.rights.length);
};
$scope.clicked = function($event, pos) {
actionLicense = true;
positionSide = pos;
currentElement = $event.currentTarget;
var deleteButton = document.getElementsByClassName("delete")[0];
if (pos === 1) {
if (deleteButton.className.indexOf("button-deactive") === -1) {
deleteButton.className += " button-deactive";
}
} else {
deleteButton.className = deleteButton.className.replace(" button-deactive", "");
}
if (prevElement === null) {
prevElement = currentElement;
} else {
if (prevElement === currentElement) {
isRepeated = !isRepeated;
} else {
if (isRepeated) {
isRepeated = false;
}
}
}
if (prevElement.className.indexOf("active") !== -1) {
prevElement.className = prevElement.className.replace(" active", "");
}
if (!isRepeated && currentElement.className.indexOf("active") === -1) {
currentElement.className += " active";
}
prevElement = currentElement;
};
});
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
padding: 0;
}
.container {
display: inline-block;
width: 100%;
padding: 10px;
height: 100vh;
border: #E64A19 inset .7vh;
background: #616161;
/* fallback for old browsers */
background: -webkit-linear-gradient(to left, #9bc5c3, #616161);
/* Chrome 10-25, Safari 5.1-6 */
background: linear-gradient(to left, #9bc5c3, #616161);
/* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
}
.addItems {
height: 10vh;
margin-bottom: 5vh;
}
.box {
float: left;
display: inline-block;
margin: 0;
padding: 10px;
height: 80vh;
border: #cfcfcf outset 2px;
color: #eee;
font-size: medium;
}
.box>div {
border: #FFF59D ridge 2px;
border-bottom: none;
border-radius: 5px;
}
.box>div>div {
padding: 7px;
border-bottom: #FFF59D ridge 2px;
}
.box>div>div:hover {
background-color: rgba(100, 150, 220, .5);
transition: background-color .4s ease;
}
.box>button {
display: inline-block;
width: 70%;
margin: 5% 15%;
}
.button {
padding: 10px 24px;
border-radius: 3px;
border: none;
box-shadow: 2px 5px 10px rgba(22, 22, 22, .1);
}
.button:hover {
transition: all 60ms ease;
opacity: .95;
box-shadow: #444 0 3px 3px 0;
}
.button-blue {
color: #FFFFFF;
background: #416dea;
}
.button-red {
color: #FFFFFF;
background: #F32C52;
}
.button-dark {
filter: brightness(85%) contrast(110%);
}
.leftBox {
width: 40%;
}
.button_holder {
width: 20%;
}
.rightBox {
width: 40%;
}
input[type="text"],
select {
padding: 5px;
}
.active {
transition: all .1s ease;
background-color: #888;
color: #000;
;
border: dotted 1px black;
box-shadow: 0 2px 2px 0 rgba(97, 97, 97, .5);
margin-bottom: 1px;
}
.button-deactive {
opacity: .5;
box-shadow: none;
}
.button-deactive:hover {
opacity: .5;
box-shadow: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AddRemoveBox</title>
<link rel="stylesheet" href="index.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<!--include angularJs-->
<script src="index.js"></script>
</head>
<body>
<div class="container" ng-app="Add_Remove_Box" ng-controller="Ctrl">
<fieldset class="addItems">
<legend>Insert Items</legend>
<select ng-model="selectedSide">
<option ng-repeat="choice in choices">{{choice}}</option>
</select>
<input type="text" ng-model="choice.name" name="" placeholder="Enter The Item Name">
<button class="button insert" value="insert" ng-click="insert($event)">Insert</button>
</fieldset>
<div class="box leftBox">
<div>
<div id="{{left.name}}" ng-click="clicked($event, 0)" data-ng-repeat="left in lefts">{{left.name}}</div>
</div>
</div>
<div class="box button_holder">
<button ng-click="add()" class="button button-blue">ADD ></button>
<button ng-click="remove()" class="button button-red">< REMOVE</button>
<button ng-click="addAll()" class="button button-blue button-dark">ADD ALL >></button>
<button ng-click="removeAll()" class="button button-red button-dark"><< REMOVE ALL</button>
<button ng-click="deleteChoice()" class="button delete">X</button>
</div>
<div class="box rightBox">
<div>
<div ng-click="clicked($event, 1)" data-ng-repeat="right in rights">{{right.name}}</div>
</div>
</div>
</div>
</body>
</html>

Doughnut code directly copied from codepen not working

I just copy pasted the code from this.Not changed anything:
http://codepen.io/anon/pen/rapJzN
but it doesn't work.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style>
#import url(//fonts.googleapis.com/css?family=Oswald:400);
body {
background: #222428;
font-family: "Oswald", sans-serif;
}
h1 {
color: #eee;
text-align: center;
margin: 20px 0;
text-transform: uppercase;
}
.chart {
margin: 0 auto;
width: 450px;
height: 450px;
position: relative;
}
.doughnutTip {
position: absolute;
float: left;
min-width: 30px;
max-width: 300px;
padding: 5px 15px;
border-radius: 1px;
background: rgba(0,0,0,.8);
color: #ddd;
font-size: 17px;
text-shadow: 0 1px 0 #000;
text-transform: uppercase;
text-align: center;
line-height: 1.3;
letter-spacing: .06em;
box-shadow: 0 1px 3px rgba(0,0,0,0.5);
transform: all .3s;
pointer-events: none;
}
.doughnutTip:after {
position: absolute;
left: 50%;
bottom: -6px;
content: "";
height: 0;
margin: 0 0 0 -6px;
border-right: 5px solid transparent;
border-left: 5px solid transparent;
border-top: 6px solid rgba(0,0,0,.7);
line-height: 0;
}
.doughnutSummary {
position: absolute;
top: 50%;
left: 50%;
color: #d5d5d5;
text-align: center;
text-shadow: 0 -1px 0 #111;
cursor: default;
}
.doughnutSummaryTitle {
position: absolute;
top: 50%;
width: 100%;
margin-top: -27%;
font-size: 22px;
letter-spacing: .06em;
}
.doughnutSummaryNumber {
position: absolute;
top: 50%;
width: 100%;
margin-top: -15%;
font-size: 55px;
}
.chart path:hover {
opacity: .65;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>Is it useful to distinguish between "web apps" and "web sites"?</h1>
<div id="doughnutChart" class="chart"></div>
</div>
<script>
$("#doughnutChart").drawDoughnutChart([
{
title: "Nope, It's all just the web",
value: 4822,
color: "#f3e32b"
},
{
title: "Yep. They are different things with different concerns",
value: 12339,
color: "#35a8ff"
}
]);
</script>
</form>
</body>
</html>
What is going wrong ? Am I missing something ?
Do I need to link it to something ? or download some file ? I am new to using codepen
you have 2 issues. First you need to include jQuery like this:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
Second, you need to include drawDoughnutChart, find the source files here:
https://github.com/githiro/drawDoughnutChart
Good luck!
[EDIT] Here os some working code, but instead of having the JS inside the html file, it should be included like jQuery...
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<style>
#import url(//fonts.googleapis.com/css?family=Oswald:400);
body {
background: #222428;
font-family: "Oswald", sans-serif;
}
h1 {
color: #eee;
text-align: center;
margin: 20px 0;
text-transform: uppercase;
}
.chart {
margin: 0 auto;
width: 450px;
height: 450px;
position: relative;
}
.doughnutTip {
position: absolute;
float: left;
min-width: 30px;
max-width: 300px;
padding: 5px 15px;
border-radius: 1px;
background: rgba(0,0,0,.8);
color: #ddd;
font-size: 17px;
text-shadow: 0 1px 0 #000;
text-transform: uppercase;
text-align: center;
line-height: 1.3;
letter-spacing: .06em;
box-shadow: 0 1px 3px rgba(0,0,0,0.5);
transform: all .3s;
pointer-events: none;
}
.doughnutTip:after {
position: absolute;
left: 50%;
bottom: -6px;
content: "";
height: 0;
margin: 0 0 0 -6px;
border-right: 5px solid transparent;
border-left: 5px solid transparent;
border-top: 6px solid rgba(0,0,0,.7);
line-height: 0;
}
.doughnutSummary {
position: absolute;
top: 50%;
left: 50%;
color: #d5d5d5;
text-align: center;
text-shadow: 0 -1px 0 #111;
cursor: default;
}
.doughnutSummaryTitle {
position: absolute;
top: 50%;
width: 100%;
margin-top: -27%;
font-size: 22px;
letter-spacing: .06em;
}
.doughnutSummaryNumber {
position: absolute;
top: 50%;
width: 100%;
margin-top: -15%;
font-size: 55px;
}
.chart path:hover {
opacity: .65;
}
</style>
<script type="application/javascript">
/*!
* jquery.drawDoughnutChart.js
* Version: 0.4(Beta)
* Inspired by Chart.js(http://www.chartjs.org/)
*
* Copyright 2014 hiro
* https://github.com/githiro/drawDoughnutChart
* Released under the MIT license.
*
*/
;(function($, undefined) {
$.fn.drawDoughnutChart = function(data, options) {
var $this = this,
W = $this.width(),
H = $this.height(),
centerX = W/2,
centerY = H/2,
cos = Math.cos,
sin = Math.sin,
PI = Math.PI,
settings = $.extend({
segmentShowStroke : true,
segmentStrokeColor : "#0C1013",
segmentStrokeWidth : 1,
baseColor: "rgba(0,0,0,0.5)",
baseOffset: 4,
edgeOffset : 10,//offset from edge of $this
percentageInnerCutout : 75,
animation : true,
animationSteps : 90,
animationEasing : "easeInOutExpo",
animateRotate : true,
tipOffsetX: -8,
tipOffsetY: -45,
showTip: true,
showLabel: false,
ratioFont: 1.5,
shortInt: false,
tipClass: "doughnutTip",
summaryClass: "doughnutSummary",
summaryTitle: "TOTAL:",
summaryTitleClass: "doughnutSummaryTitle",
summaryNumberClass: "doughnutSummaryNumber",
beforeDraw: function() { },
afterDrawed : function() { },
onPathEnter : function(e,data) { },
onPathLeave : function(e,data) { }
}, options),
animationOptions = {
linear : function (t) {
return t;
},
easeInOutExpo: function (t) {
var v = t<.5 ? 8*t*t*t*t : 1-8*(--t)*t*t*t;
return (v>1) ? 1 : v;
}
},
requestAnimFrame = function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
}();
settings.beforeDraw.call($this);
var $svg = $('<svg width="' + W + '" height="' + H + '" viewBox="0 0 ' + W + ' ' + H + '" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"></svg>').appendTo($this),
$paths = [],
easingFunction = animationOptions[settings.animationEasing],
doughnutRadius = Min([H / 2,W / 2]) - settings.edgeOffset,
cutoutRadius = doughnutRadius * (settings.percentageInnerCutout / 100),
segmentTotal = 0;
//Draw base doughnut
var baseDoughnutRadius = doughnutRadius + settings.baseOffset,
baseCutoutRadius = cutoutRadius - settings.baseOffset;
$(document.createElementNS('http://www.w3.org/2000/svg', 'path'))
.attr({
"d": getHollowCirclePath(baseDoughnutRadius, baseCutoutRadius),
"fill": settings.baseColor
})
.appendTo($svg);
//Set up pie segments wrapper
var $pathGroup = $(document.createElementNS('http://www.w3.org/2000/svg', 'g'));
$pathGroup.attr({opacity: 0}).appendTo($svg);
//Set up tooltip
if (settings.showTip) {
var $tip = $('<div class="' + settings.tipClass + '" />').appendTo('body').hide(),
tipW = $tip.width(),
tipH = $tip.height();
}
//Set up center text area
var summarySize = (cutoutRadius - (doughnutRadius - cutoutRadius)) * 2,
$summary = $('<div class="' + settings.summaryClass + '" />')
.appendTo($this)
.css({
width: summarySize + "px",
height: summarySize + "px",
"margin-left": -(summarySize / 2) + "px",
"margin-top": -(summarySize / 2) + "px"
});
var $summaryTitle = $('<p class="' + settings.summaryTitleClass + '">' + settings.summaryTitle + '</p>').appendTo($summary);
$summaryTitle.css('font-size', getScaleFontSize( $summaryTitle, settings.summaryTitle )); // In most of case useless
var $summaryNumber = $('<p class="' + settings.summaryNumberClass + '"></p>').appendTo($summary).css({opacity: 0});
for (var i = 0, len = data.length; i < len; i++) {
segmentTotal += data[i].value;
$paths[i] = $(document.createElementNS('http://www.w3.org/2000/svg', 'path'))
.attr({
"stroke-width": settings.segmentStrokeWidth,
"stroke": settings.segmentStrokeColor,
"fill": data[i].color,
"data-order": i
})
.appendTo($pathGroup)
.on("mouseenter", pathMouseEnter)
.on("mouseleave", pathMouseLeave)
.on("mousemove", pathMouseMove)
.on("click", pathClick);
}
//Animation start
animationLoop(drawPieSegments);
//Functions
function getHollowCirclePath(doughnutRadius, cutoutRadius) {
//Calculate values for the path.
//We needn't calculate startRadius, segmentAngle and endRadius, because base doughnut doesn't animate.
var startRadius = -1.570,// -Math.PI/2
segmentAngle = 6.2831,// 1 * ((99.9999/100) * (PI*2)),
endRadius = 4.7131,// startRadius + segmentAngle
startX = centerX + cos(startRadius) * doughnutRadius,
startY = centerY + sin(startRadius) * doughnutRadius,
endX2 = centerX + cos(startRadius) * cutoutRadius,
endY2 = centerY + sin(startRadius) * cutoutRadius,
endX = centerX + cos(endRadius) * doughnutRadius,
endY = centerY + sin(endRadius) * doughnutRadius,
startX2 = centerX + cos(endRadius) * cutoutRadius,
startY2 = centerY + sin(endRadius) * cutoutRadius;
var cmd = [
'M', startX, startY,
'A', doughnutRadius, doughnutRadius, 0, 1, 1, endX, endY,//Draw outer circle
'Z',//Close path
'M', startX2, startY2,//Move pointer
'A', cutoutRadius, cutoutRadius, 0, 1, 0, endX2, endY2,//Draw inner circle
'Z'
];
cmd = cmd.join(' ');
return cmd;
};
function pathMouseEnter(e) {
var order = $(this).data().order;
if (settings.showTip) {
$tip.text(data[order].title + ": " + data[order].value)
.fadeIn(200);
}
if(settings.showLabel) {
$summaryTitle.text(data[order].title).css('font-size', getScaleFontSize( $summaryTitle, data[order].title));
var tmpNumber = settings.shortInt ? shortKInt(data[order].value) : data[order].value;
$summaryNumber.html(tmpNumber).css('font-size', getScaleFontSize( $summaryNumber, tmpNumber));
}
settings.onPathEnter.apply($(this),[e,data]);
}
function pathMouseLeave(e) {
if (settings.showTip) $tip.hide();
if(settings.showLabel) {
$summaryTitle.text(settings.summaryTitle).css('font-size', getScaleFontSize( $summaryTitle, settings.summaryTitle));
var tmpNumber = settings.shortInt ? shortKInt(segmentTotal) : segmentTotal;
$summaryNumber.html(tmpNumber).css('font-size', getScaleFontSize( $summaryNumber, tmpNumber));
}
settings.onPathLeave.apply($(this),[e,data]);
}
function pathMouseMove(e) {
if (settings.showTip) {
$tip.css({
top: e.pageY + settings.tipOffsetY,
left: e.pageX - $tip.width() / 2 + settings.tipOffsetX
});
}
}
function pathClick(e){
var order = $(this).data().order;
if (typeof data[order].action != "undefined")
data[order].action();
}
function drawPieSegments (animationDecimal) {
var startRadius = -PI / 2,//-90 degree
rotateAnimation = 1;
if (settings.animation && settings.animateRotate) rotateAnimation = animationDecimal;//count up between0~1
drawDoughnutText(animationDecimal, segmentTotal);
$pathGroup.attr("opacity", animationDecimal);
//If data have only one value, we draw hollow circle(#1).
if (data.length === 1 && (4.7122 < (rotateAnimation * ((data[0].value / segmentTotal) * (PI * 2)) + startRadius))) {
$paths[0].attr("d", getHollowCirclePath(doughnutRadius, cutoutRadius));
return;
}
for (var i = 0, len = data.length; i < len; i++) {
var segmentAngle = rotateAnimation * ((data[i].value / segmentTotal) * (PI * 2)),
endRadius = startRadius + segmentAngle,
largeArc = ((endRadius - startRadius) % (PI * 2)) > PI ? 1 : 0,
startX = centerX + cos(startRadius) * doughnutRadius,
startY = centerY + sin(startRadius) * doughnutRadius,
endX2 = centerX + cos(startRadius) * cutoutRadius,
endY2 = centerY + sin(startRadius) * cutoutRadius,
endX = centerX + cos(endRadius) * doughnutRadius,
endY = centerY + sin(endRadius) * doughnutRadius,
startX2 = centerX + cos(endRadius) * cutoutRadius,
startY2 = centerY + sin(endRadius) * cutoutRadius;
var cmd = [
'M', startX, startY,//Move pointer
'A', doughnutRadius, doughnutRadius, 0, largeArc, 1, endX, endY,//Draw outer arc path
'L', startX2, startY2,//Draw line path(this line connects outer and innner arc paths)
'A', cutoutRadius, cutoutRadius, 0, largeArc, 0, endX2, endY2,//Draw inner arc path
'Z'//Cloth path
];
$paths[i].attr("d", cmd.join(' '));
startRadius += segmentAngle;
}
}
function drawDoughnutText(animationDecimal, segmentTotal) {
$summaryNumber
.css({opacity: animationDecimal})
.text((segmentTotal * animationDecimal).toFixed(1));
var tmpNumber = settings.shortInt ? shortKInt(segmentTotal) : segmentTotal;
$summaryNumber.html(tmpNumber).css('font-size', getScaleFontSize( $summaryNumber, tmpNumber));
}
function animateFrame(cnt, drawData) {
var easeAdjustedAnimationPercent =(settings.animation)? CapValue(easingFunction(cnt), null, 0) : 1;
drawData(easeAdjustedAnimationPercent);
}
function animationLoop(drawData) {
var animFrameAmount = (settings.animation)? 1 / CapValue(settings.animationSteps, Number.MAX_VALUE, 1) : 1,
cnt =(settings.animation)? 0 : 1;
requestAnimFrame(function() {
cnt += animFrameAmount;
animateFrame(cnt, drawData);
if (cnt <= 1) {
requestAnimFrame(arguments.callee);
} else {
settings.afterDrawed.call($this);
}
});
}
function Max(arr) {
return Math.max.apply(null, arr);
}
function Min(arr) {
return Math.min.apply(null, arr);
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function CapValue(valueToCap, maxValue, minValue) {
if (isNumber(maxValue) && valueToCap > maxValue) return maxValue;
if (isNumber(minValue) && valueToCap < minValue) return minValue;
return valueToCap;
}
function shortKInt (int) {
int = int.toString();
var strlen = int.length;
if(strlen<5)
return int;
if(strlen<8)
return '<span title="' + int + '">' + int.substring(0, strlen-3) + 'K</span>';
return '<span title="' + int + '">' + int.substring( 0, strlen-6) + 'M</span>';
}
function getScaleFontSize(block, newText) {
block.css('font-size', '');
newText = newText.toString().replace(/(<([^>]+)>)/ig,"");
var newFontSize = block.width() / newText.length * settings.ratioFont;
// Not very good : http://stephensite.net/WordPressSS/2008/02/19/how-to-calculate-the-character-width-accross-fonts-and-points/
// But best quick way the 1.5 number is to affinate in function of the police
var maxCharForDefaultFont = block.width() - newText.length * block.css('font-size').replace(/px/, '') / settings.ratioFont;
if(maxCharForDefaultFont<0)
return newFontSize+'px';
else
return '';
}
/**
function getScaleFontSize(block, newText) {
block.css('font-size', '');
newText = newText.toString().replace(/(<([^>]+)>)/ig,"");
var newFontSize = block.width() / newText.length;
if(newFontSize<block.css('font-size').replace(/px/, ''))
return newFontSize+'px';
else
return '';
}*/
return $this;
};
})(jQuery);
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>Is it useful to distinguish between "web apps" and "web sites"?</h1>
<div id="doughnutChart" class="chart"></div>
</div>
<script>
$("#doughnutChart").drawDoughnutChart([
{
title: "Nope, It's all just the web",
value: 4822,
color: "#f3e32b"
},
{
title: "Yep. They are different things with different concerns",
value: 12339,
color: "#35a8ff"
}
]);
</script>
</form>
</body>
</html>
[EDIT2]
Also, use your browsers developer tools (usually F12) to see what error messages comes up... On your first example, the error was $ is undefined or something, and this usually means that jQuery is needed. After that it said drawDoughnutChart() is undefined, and a quick google search got me the sourcecode needed...
Just add this at the beginning of your <head>:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://raw.githubusercontent.com/githiro/drawDoughnutChart/master/jquery.drawDoughnutChart.js"></script>
Problem solved :)

Categories

Resources