Multiple progress bars visualy update only one - javascript

i'm working on my JavaScript skills and this is my first program trial here.
Everything was going quite well for me, but i'm stuck on this problem for about 3 days now and i guess there is something i don't get over here.
Well, diving in - i have 2 separate "Training Fields" - each has it's own "Train" button (onclick function) , "Level up" button (onclick function) and progress bar.
The problem is that the higher "Training Field" will progress the lower progress bar and not it's own.
Help will be appreciated! thx
//ignore this line, it's for me for testing
document.getElementById('hideMe').style.visibility = 'hidden';
/*========================================
Javascript for first set
========================================*/
var bodyTotal = 0;
var totalBodyCost = 0;
var bodyCost = 100;
var amountLoaded = 1;
function buyBody(){
bodyCost = totalBodyCost + Math.floor(100 * Math.pow(1.1,bodyTotal));
if(amountLoaded >= bodyCost){
totalBodyCost += bodyCost;
bodyTotal = bodyTotal + 1;
document.getElementById('bodyTotal').innerHTML = bodyTotal;
var finalMessage = document.getElementById('bodyFinalMessage').style.visibility = 'hidden';
amountLoaded = 0;
};
var nextCost = totalBodyCost + Math.floor(100 * Math.pow(1.1,bodyTotal));
document.getElementById('bodyCost').innerHTML = nextCost;
document.getElementById("bodyProgressBar").max = nextCost;
bodyCost = nextCost;
progressBarSim(amountLoaded);
};
function progressBarSim(al) {
var bar = document.getElementById('bodyProgressBar');
var status = document.getElementById('bodyStatus');
status.innerHTML = al+"/" +bodyCost;
bar.value = al;
al++;
var sim = "progressBarSim("+al+")";
}
function trainBody(){
progressBarSim(amountLoaded);
if(amountLoaded < bodyCost){
amountLoaded++;
}else{
var finalMessage = document.getElementById('bodyFinalMessage').style.visibility = 'visible';
finalMessage.innerHTML = "";
}
};
/*=============================================*/
/*========================================
Javascript for second set
========================================*/
var mindTotal = 0;
var totalMindCost = 0;
var mindCost = 100;
var amountLoaded = 1;
function buyMind(){
mindCost = totalMindCost + Math.floor(100 * Math.pow(1.1,mindTotal));
if(amountLoaded >= mindCost){
totalMindCost += mindCost;
mindTotal = mindTotal + 1;
document.getElementById('mindTotal').innerHTML = mindTotal;
var finalMessage = document.getElementById('mindFinalMessage').style.visibility = 'hidden';
amountLoaded = 0;
};
var nextCost = totalMindCost + Math.floor(100 * Math.pow(1.1,mindTotal));
document.getElementById('mindCost').innerHTML = nextCost;
document.getElementById("mindProgressBar").max = nextCost;
mindCost = nextCost;
progressBarSim(amountLoaded);
};
function progressBarSim(al) {
var bar = document.getElementById('mindProgressBar');
var status = document.getElementById('mindStatus');
status.innerHTML = al+"/" +mindCost;
bar.value = al;
al++;
var sim = "progressBarSim("+al+")";
}
function trainMind(){
progressBarSim(amountLoaded);
if(amountLoaded < mindCost){
amountLoaded++;
}else{
var finalMessage = document.getElementById('mindFinalMessage').style.visibility = 'visible';
finalMessage.innerHTML = "";
}
};
/*=============================================*/
<html>
<head>
<link rel="stylesheet" type="text/css" href="interface.css" />
</head>
<body>
<div style="float:right">
Body Level: <span id="bodyTotal">0</span>
<button onclick="trainBody()">Train Body</button><br>
<progress id="bodyProgressBar" value="0" max="100" style="width:200px; float:left;"></progress>
<span id="bodyStatus" style="float:left; z-index:555; margin-left:-110px;">0/100</span>
<button id="bodyFinalMessage" style="float:left; visibility:hidden" onclick="buyBody()">Body Level Up</button>
<br><br>
Mind Level: <span id="mindTotal">0</span>
<button onclick="trainMind()">Train Mind</button><br>
<progress id="mindProgressBar" value="0" max="100" style="width:200px; float:left;"></progress>
<span id="mindStatus" style="float:left; z-index:555; margin-left:-110px;">0/100</span>
<button id="mindFinalMessage" style="float:left; visibility:hidden" onclick="buyMind()">Mind Level Up</button>
</div>
<div id="hideMe" style="position:absolute; top:400; left:400">
Body Cost: <span id="bodyCost">100</span><br>
Mind Cost: <span id="mindCost">100</span>
</div>
<script type="text/javascript" src="main.js"></script>
</body>
</html>

You are reassigning variables and functions using the exact same names amountLoaded, progressBarSim(al).
Because body and mind behavior are very similar you could use a module pattern (http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html) to use the same variable and function names within their own scopes.
<button onclick="Body.onClick()">Body</button>
<button onclick="Mind.onClick()">Mind</button>
And in your script file
var Body = (function() {
var me = {};
me.onClick = function() {
console.log("body click");
progressBar(al);
};
function progressBar(al) {
}
return me;
})();
var Mind = (function() {
var me = {};
me.onClick = function() {
console.log("mind click");
progressBar(al);
};
function progressBar(al) {
}
return me;
})();
The gotcha here is you can't use body with the inline onclick since that already refers to the body element.

Related

I remove a file that I uploaded, I got a error

When I remove a file that I uploaded, I got a error. That is js:42 Uncaught TypeError: Cannot read property 'removeChild' of null. I have to use removeChild and var for IE. Is there a good way to fix the error?
html
<form action="" enctype="multipart/form-data" class="page_form">
<label class="ui_upload upload_label" for="upload-doc">
<input type="file" name="file" id="upload-doc"
accept=".pdf,.doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
multiple />
<span class="btn sm label upload_btn">upload file</span>
</label>
<div class="upload_documents_wrap visually_hide">
<div class="upload_documents"> </div>
</div>
<div class="visually_hide" id="upload-file">
<div class="upload_info shadow light upload_file">
<span class="tit sm file_name"> </span>
<span class="tit sm file_size"> </span>
<button class="file_remove" type="button">Remove</button>
</div>
</div>
<button type="submit" class="btn sm">submit</button>
</form>
js
(function () {
var formElement = document.querySelector(".page_form");
var fileChooserEl = formElement.querySelector('.upload_label input[type="file"]');
var uploadDocumentsWrap = formElement.querySelector(".upload_documents_wrap");
var uploadDocuments = uploadDocumentsWrap.querySelector(".upload_documents");
var templateItemParent = document.querySelector("#upload-file");
var templateItem = templateItemParent.querySelector(".upload_file");
var uploadFiles = [];
var myFileList = [];
var onFileChooserChange = function () {
for (var i = 0; i < fileChooserEl.files.length; i++) {
var position = templateItem.cloneNode(true);
var uploadFileName = position.querySelector(".file_name");
var uploadFileSize = position.querySelector(".file_size");
var uploadFileRemove = position.querySelector(".file_remove");
var fileName = fileChooserEl.files[i].name.toLowerCase();
uploadDocumentsWrap.classList.remove("visually_hide");
uploadFileName.textContent = fileName; // file size
var suffix = "bytes";
var size = fileChooserEl.files[i].size;
if (size >= 1024 && size < 1024000) {
suffix = "KB";
size = Math.round(size / 1024 * 100) / 100;
} else if (size >= 1024000) {
suffix = "MB";
size = Math.round(size / 1024000 * 100) / 100;
}
uploadFileSize.textContent = size + suffix;
uploadFileRemove.addEventListener("click", function (evt) {
evt.preventDefault();
myFileList = myFileList.filter(function (item) {
return item.name.toLowerCase() !== uploadFileRemove.previousElementSibling.textContent;
});
console.log(myFileList);
var index = uploadFiles.indexOf(evt.target.parentNode);
uploadFileRemove.parentNode.parentNode.removeChild(uploadFileRemove.parentNode);
uploadFiles.splice(index, 1);
myFileList.splice(index, 1);
console.log(index);
if (!uploadFiles.length) {
uploadDocumentsWrap.classList.add("visually_hide");
}
});
uploadDocuments.appendChild(position);
uploadFiles.push(position);
myFileList.push(fileChooserEl.files[i]);
}
fileChooserEl.value = "";
};
console.log(uploadFiles);
var getFormData = function () {
var data = new FormData(formElement);
for (var i = 0; i < myFileList.length; i += 1) {
data.append(fileChooserEl.name, myFileList[i]);
}
return data;
};
fileChooserEl.addEventListener("change", onFileChooserChange);
})();
The error is on this line:
uploadFileRemove.parentNode.parentNode.removeChild(uploadFileRemove.parentNode);
I debugged the code and find that you removed wrong file every time when clicking the "Remove" button. It's easier and more clear to identify which file to remove using index. I edit the code like this and it works well:
...
var index = uploadFiles.indexOf(evt.target.parentNode);
//edit
var removefile = document.querySelectorAll(".upload_info")[index];
uploadDocuments.removeChild(removefile);
//uploadFileRemove.parentNode.parentNode.removeChild(uploadFileRemove.parentNode);
uploadFiles.splice(index, 1);
myFileList.splice(index, 1);
console.log(index);
...
Result:

JS get random value from array and update array

I need your help on this!
I'm generating an array which corresponds to a question number.
var arrayCharge = [];
for (var i = 2; i <= 45; i++) {
arrayCharge.push(i);
}
then I use this number to append the corresponding question, answer then click.
Then I'm getting a new value from the array like this
const randomQ = arrayCharge;
const random = Math.floor(Math.random() * randomQ.length);
It works and a new question is charged but the array is still the same.
I've tried this
var remQ = arrayCharge.indexOf(randomQ[random]);
arrayCharge.splice(remQ,1);
But It doesn't work ;-(
Thanks a lot for your help.
Nicolas
Here is the entire code to help comprehension! sorry for that, I should have done it from the begining.
<!DOCTYPE HTML>
<!--
Hyperspace by HTML5 UP
html5up.net | #ajlkn
Free for personal and commercial use under the CCA 3.0 license (html5up.net/license)
-->
<html>
<head>
<title>Repérez vos messages contraignants - Quiz</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="stylesheet" href="assets/css/main.css" />
<noscript>
<link rel="stylesheet" href="assets/css/noscript.css" /></noscript>
</head>
<body class="is-preload">
<!-- Sidebar -->
<!-- <section id="sidebar">
</section> -->
<!-- Wrapper -->
<div id="wrapper">
<!-- Intro -->
<section id="intro" class="wrapper style1 fullscreen fade-up">
<div class="inner">
<header>
<button id="start">Commencer</button>
<p> </p>
</header>
<form action="" method="post">
<p id="Qnum"></p>
<p id="Q" data-qnumber="" data-type=""></p>
<section id="answer">
<input type="submit" id="1" name="R1" value="Non">
<input type="submit" id="2" name="R2" value="Parfois">
<input type="submit" id="3" name="R3" value="Souvent">
<input type="submit" id="4" name="R4" value="Oui">
</section>
</form>
</div>
</section>
<!-- Footer -->
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.scrollex.min.js"></script>
<script src="assets/js/jquery.scrolly.min.js"></script>
<script src="assets/js/browser.min.js"></script>
<script src="assets/js/breakpoints.min.js"></script>
<script src="assets/js/util.js"></script>
<script src="assets/js/main.js"></script>
<script>
$(document).ready(function() {
if (localStorage.getItem("clic") >= 45) {
console.log('45');
sessionStorage.clear();
localStorage.clear();
}
var Q1 = [1, "My first question", "FP"];
var Q2 = [2, "My second question", "SP"];
var Q3 = [3, "My third question", "SE"];
var Q4 = [4, "My foutrh question", "DP"];
var Q5 = [5, "My fifth question", "FP"];
//etc... until Q45
if (sessionStorage.getItem("FP") == null) {
$("form").attr("action", "driversV2.php");
$("#answer").hide();
$("#start").click(function() {
$("#Qnum").append(1+" / 45");
$("#Q").append(Q1[1]).attr("data-qnumber", Q1[0]).attr("data-type", Q1[2]);
$("#answer").show();
$("header").hide();
var pageType = $("#Q").attr("data-type");
$("input").click(function() {
var reponse = this.id;
sessionStorage.setItem(pageType, reponse);
localStorage.setItem("clic", 1);
});
});
} else {
$("header").hide();
var clicNum = parseInt(localStorage.getItem("clic"));
var QNumber = clicNum + 1;
var arrayCharge = [];
for (var i = 2; i <= 45; i++) {
arrayCharge.push(i);
}
const randomQ = arrayChargeNew;
const random = Math.floor(Math.random() * randomQ.length);
console.log('valeur random new = '+randomQ[random]);
var QCharge = "Q" + randomQ[random];
var Charge = eval(QCharge);
localStorage.setItem("random",randomQ[random]);
$("#Qnum").append(QNumber+" / 45");
$("#Q").append(Charge[1]).attr("data-qnumber", Charge[0]).attr("data-type", Charge[2]);
//création de la variable du type de question
var pageType = $("#Q").attr("data-type");
//alert(sessionStorage.getItem(pageType));
if (localStorage.getItem("clic") < 44) {
$("form").attr("action", "driversV2.php");
if (sessionStorage.getItem(pageType) != null) {
var x = parseInt(sessionStorage.getItem(pageType));
$("input").click(function() {
var reponse = parseInt(this.id);
var addition = reponse + x;
sessionStorage.setItem(pageType, addition);
var clic = parseInt(localStorage.getItem("clic"));
localStorage.setItem("clic", clic + 1);
});
} else {
$("input").click(function() {
var reponse = this.id;
sessionStorage.setItem(pageType, reponse);
var clic = parseInt(localStorage.getItem("clic"));
localStorage.setItem("clic", clic + 1);
});
}
} else {
$("form").attr("action", "driversResultat.php");
if (sessionStorage.getItem(pageType) != null) {
var x = parseInt(sessionStorage.getItem(pageType));
$("input").click(function() {
var reponse = parseInt(this.id);
var addition = reponse + x;
sessionStorage.setItem(pageType, addition);
var clic = parseInt(localStorage.getItem("clic"));
localStorage.setItem("clic", clic + 1);
});
} else {
$("input").click(function() {
var reponse = this.id;
sessionStorage.setItem(pageType, reponse);
var clic = parseInt(localStorage.getItem("clic"));
localStorage.setItem("clic", clic + 1);
});
}
}
}
});
</script>
</body>
</html>
Nicolas, this is the sort of thing you should end up with:
// From my library js file
// returns a random number in the given range
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Variables for objects that need to be available throughout
let availableQuestions = [];
let rnd = 0;
let counter = 0;
// Populate the question array - how this is done depends on where the question data comes from
function createQuestions() {
availableQuestions.length = 0;
for (let i = 1; i <= 10; i++) {
availableQuestions.push({"questionnumber": i, "question": "Text for question " + i});
}
}
// Pick a random question and display that to the user
function getRandomQuestion() {
let osQuestions = availableQuestions.length;
let qnElement = document.getElementById("questionnumber");
let qElement = document.getElementById("question");
let sButton = document.getElementById("submit");
let rButton = document.getElementById("restart");
// If there are no more questions, stop
if (osQuestions == 0) {
qnElement.innerHTML = "Finished!";
qElement.innerHTML = "";
sButton.style.display = "none";
rButton.style.display = "inline";
} else {
// display a sequential question number rather than the actual question number
counter++;
rnd = getRandomNumber(0, osQuestions - 1);
let thisQuestion = availableQuestions[rnd];
qnElement.innerHTML = "Question: " + counter + " (Actually question: " + thisQuestion.questionnumber + ")";
qElement.innerHTML = thisQuestion.question;
}
}
// Process the user's answer and remove the question from the array
function submitAnswer() {
// ALSO Add in what needs to be done to update backend database etc when the user clicks submit
availableQuestions.splice(rnd, 1);
getRandomQuestion();
}
// Reset everything - for testing purposes only
function restart() {
let qnElement = document.getElementById("questionnumber");
let qElement = document.getElementById("question");
let sButton = document.getElementById("submit");
let rButton = document.getElementById("restart");
qnElement.innerHTML = "";
qElement.innerHTML = "";
sButton.style.display = "inline";
rButton.style.display = "none";
// Reset the displayed question number counter
counter = 0;
createQuestions();
getRandomQuestion();
}
// Needed to populate the array and display the first question
function runsetup() {
createQuestions();
getRandomQuestion();
}
window.onload = runsetup;
<div id="questionnumber"></div>
<hr>
<div id="question"></div>
<button id="submit" onclick="submitAnswer();">Submit</button>
<button id="restart" onclick="restart();" style="display:none;">Restart</button>
I've included a counter variable so that the user does't see the actual question number - just 1, 2, 3 etc but I've shown the actual question number so that you can see it working
Nicolas, this is what I think you should be doing:
// Create the array in whatever way you need to
var arrayCharge = [];
for (var i = 2; i <= 45; i++) {
arrayCharge.push({"questionnumber": i, "question": "Text of question " + i});
}
// Just confirm the length of the array - should be 44
console.log(arrayCharge.length);
// Generate a random number based on the length of the array
var rnd = Math.floor(Math.random() * arrayCharge.length);
// Get the question at the randomly generated index number
let thisQuestion = arrayCharge[rnd];
// Check that we have a random question
console.log(thisQuestion.questionnumber);
console.log(thisQuestion.question)
// Present the question to the user on the page
// The user completes question and clicks "Submit"
// Now remove the question, using the SAME index number
arrayCharge.splice(rnd,1);
// Check that the array has lost an entry - the size should now be 43
console.log(arrayCharge.length);

Displaying hidden html buttons using JavaScript

Am trying to create a quiz but after the start page am un sure how to make the answer choices display. I have created the buttons for the choices in html and started them off as hidden, and have allocated for them in javascript. I have the questions and answers in an array but am stuck on displaying the choice buttons under the question. After the initial start page.
<div class="wrapper text-center">
<header>
<h1>Coding Quiz</h1>
</header>
<div class="card">
</div>
<div class="card-body">
<p id="header"> You have 75 seconds to complete this asessment. Every
incorrect answer will cost you time.
<br>
</p>
<button id="start-button" class="btn">Start</button>
<div id="start-game" style="visibility: hidden">
<button id="option0" data-index="0"></button><br>
<button id="option1" data-index="1"></button><br>
<button id="option2" data-index="2"></button><br>
<button id="option3" data-index="3"></button><br>
</div>
</div>
</div>
var timerEl = document.getElementById("timer");
var start = document.getElementById("start-button");
var questionEl = document.getElementById("header");
var option0 = document.getElementById("option0");
var option1 = document.getElementById("option1");
var option2 = document.getElementById("option2");
var option3 = document.getElementById("option3");
var intials = document.getElementById("user-initials");
var buttonEl = document.querySelector("start-game");
var totalTime = 75;
var elapsedTime = 0;
var questionNum = 0;
var questions =["The condition in an if/else statement is enclosed with in _______",
"Arrays in JavaScript can be used to store ______",
"Commonly used data types do not include ______",
"String values must be enclosed within _____ when being assigned to variables"];
var answers =[question1= ["Quotes","Curly brackets","Parentheses","Square brackets"],
question2= ["Numbers and strings","Other arrays","Booleans","All of the above"],
question3= ["Strings","Booleans","Alerts","Numbers"],
question4= ["Commas","Curly brackets","quotes","parentheses"]
];
var correctAnswers = [2,3,2,2];
start.addEventListener("click", function(){
timer();
displayQuestion();
start.style.visibility = "hidden";
buttonEl.style.visibility = "visible";
});
function timer(){
var timerInterval = setInterval(function(){
totalTime--;
timerEl.textContent = totalTime;
if(totalTime === 0){
function stopTimer(){
clearInterval(timerInterval);
endQuiz();
return;
}
}
}, 1000)
}
function newQuiz(){
questionEl.textContent = (questions[0]);
};
function decreaseTimer (){
timerEl.text(totalTime);
while(elapsedTime < 75){
elapesedTime += 1;
}
endQuiz();
totalTime = totalTime - elapsedTime;
timerEl.textContent = totalTime;
}
function displayQuestion(){
for( var i = 0; i < questions.length ; i++){
questionEl.textContent=(questions[i]);
option0.textContent=(answers[i][0]);
option1.textContent=(answers[i][1]);
option2.textContent=(answers[i][2]);
option3.textContent=(answers[i][3]);
}
}
var buttonEl = document.querySelector("start-game");
should be
var buttonEl = document.getElementById("start-game");
var timerEl = document.getElementById("timer");
var start = document.getElementById("start-button");
var questionEl = document.getElementById("header");
var option0 = document.getElementById("option0");
var option1 = document.getElementById("option1");
var option2 = document.getElementById("option2");
var option3 = document.getElementById("option3");
var intials = document.getElementById("user-initials");
var buttonEl = document.getElementById("start-game");
var totalTime = 75;
var elapsedTime = 0;
var questionNum = 0;
var questions =["The condition in an if/else statement is enclosed with in _______",
"Arrays in JavaScript can be used to store ______",
"Commonly used data types do not include ______",
"String values must be enclosed within _____ when being assigned to variables"];
var answers =[question1= ["Quotes","Curly brackets","Parentheses","Square brackets"],
question2= ["Numbers and strings","Other arrays","Booleans","All of the above"],
question3= ["Strings","Booleans","Alerts","Numbers"],
question4= ["Commas","Curly brackets","quotes","parentheses"]
];
var correctAnswers = [2,3,2,2];
start.addEventListener("click", function(){
timer();
displayQuestion();
start.style.visibility = "hidden";
buttonEl.style.visibility = "visible";
});
function timer(){
var timerInterval = setInterval(function(){
totalTime--;
timerEl.textContent = totalTime;
if(totalTime === 0){
function stopTimer(){
clearInterval(timerInterval);
endQuiz();
return;
}
}
}, 1000)
}
function newQuiz(){
questionEl.textContent = (questions[0]);
};
function decreaseTimer (){
timerEl.text(totalTime);
while(elapsedTime < 75){
elapesedTime += 1;
}
endQuiz();
totalTime = totalTime - elapsedTime;
timerEl.textContent = totalTime;
}
function displayQuestion(){
for( var i = 0; i < questions.length ; i++){
questionEl.textContent=(questions[i]);
option0.textContent=(answers[i][0]);
option1.textContent=(answers[i][1]);
option2.textContent=(answers[i][2]);
option3.textContent=(answers[i][3]);
}
}
<div class="wrapper text-center">
<header>
<h1>Coding Quiz</h1>
</header>
<div class="card">
</div>
<div class="card-body">
<p id="header"> You have 75 seconds to complete this asessment. Every
incorrect answer will cost you time.
<br>
</p>
<button id="start-button" class="btn">Start</button>
<div id="start-game" style="visibility: hidden">
<button id="option0" data-index="0"></button><br>
<button id="option1" data-index="1"></button><br>
<button id="option2" data-index="2"></button><br>
<button id="option3" data-index="3"></button><br>
</div>
</div>
</div>
<div id="timer"></div>

Counting different input values, add them and show result

I want to make a "drink counter". There are 3 inputs which add another drink onclick. Every drink has a specific value in alcohol (var bier, var wein, var soju).
So on every count up (click), the script is supposed to:
count up the value in the respective input [this works]
add up all the numbers and drinks multiplied by their alcohol value, so added_up = bier_full + soju_full + wein_full;
If you look at the code, you will notice that I'm quite the noob. Help would be much appreciated. I can't think of a way to add all the drinks*alc. values up and display them in the id="status".
HTML:
var full = 100;
var bier = 12.7;
var wein = 10;
var soju = 3.5;
status = document.getElementById("status");
var bier_c = parseInt(document.getElementById("beer").value);
var soju_c = parseInt(document.getElementById("soju").value);
var wein_c = parseInt(document.getElementById("wine").value);
var bier_i = document.getElementById("bier_info");
var soju_i = document.getElementById("soju_info");
var wein_i = document.getElementById("wein_info");
function reset() {
bier_c = 0;
soju_c = 0;
wein_c = 0;
document.getElementById("beer").value = "0";
document.getElementById("soju").value = "0";
document.getElementById("wine").value = "0";
};
function bier_s() {
bier_c++;
document.getElementById("beer").value = bier_c;
bier_full = bier_c * bier;
bier_i.innerHTML = bier_full;
return bier_full;
};
function soju_s() {
soju_c++;
document.getElementById("soju").value = soju_c;
soju_full = soju_c * soju;
soju_i.innerHTML = soju_full;
return soju_full;
};
function wein_s() {
wein_c++;
document.getElementById("wine").value = wein_c;
wein_full = wein_c * wein;
wein_i.innerHTML = wein_full;
return wein_full;
};
added_up = bier_full + soju_full + wein_full;
alert(added_up);
<label>Beer</label><input id="beer" type="button" style="width: 50px;" onclick="bier_s();" value="0">
<label>Soju</label><input id="soju" type="button" style="width: 50px;" onclick="soju_s();" value="0">
<label>Wine</label><input id="wine" type="button" style="width: 50px;" onclick="wein_s();" value="0">
<br/>
<h2 class="c_red" id="status">Let's go!</h2>
<div class="am_info">
<p>Bier: <span id="bier_info"></span></p>
<p>Soju: <span id="soju_info"></span></p>
<p>Wine: <span id="wein_info"></span></p>
</div>
just add a method that runs every time the other methods runs =D
var full = 100;
var bier = 12.7;
var wein = 10;
var soju = 3.5;
var bier_full = 0, soju_full = 0, wein_full = 0;
status = document.getElementById("status");
var bier_c = parseInt(document.getElementById("beer").value);
var soju_c = parseInt(document.getElementById("soju").value);
var wein_c = parseInt(document.getElementById("wine").value);
var bier_i = document.getElementById("bier_info");
var soju_i = document.getElementById("soju_info");
var wein_i = document.getElementById("wein_info");
function reset() {
bier_c = 0;
soju_c = 0;
wein_c = 0;
document.getElementById("beer").value = "0";
document.getElementById("soju").value = "0";
document.getElementById("wine").value = "0";
};
function bier_s() {
bier_c++;
document.getElementById("beer").value = bier_c;
bier_full = bier_c * bier;
bier_i.innerHTML = bier_full;
addUp()
return bier_full;
};
function soju_s() {
soju_c++;
document.getElementById("soju").value = soju_c;
soju_full = soju_c * soju;
soju_i.innerHTML = soju_full;
addUp()
return soju_full;
};
function wein_s() {
wein_c++;
document.getElementById("wine").value = wein_c;
wein_full = wein_c * wein;
wein_i.innerHTML = wein_full;
addUp()
return wein_full;
};
function addUp(){
added_up = bier_full + soju_full + wein_full;
alert(added_up);
}
<label>Beer</label><input id="beer" type="button" style="width: 50px;" onclick="bier_s();" value="0">
<label>Soju</label><input id="soju" type="button" style="width: 50px;" onclick="soju_s();" value="0">
<label>Wine</label><input id="wine" type="button" style="width: 50px;" onclick="wein_s();" value="0">
<br/>
<h2 class="c_red" id="status">Let's go!</h2>
<div class="am_info">
<p>Bier: <span id="bier_info"></span></p>
<p>Soju: <span id="soju_info"></span></p>
<p>Wine: <span id="wein_info"></span></p>
</div>

JavaScript Not Triggering

So I've got the beginnings of an animation script here:
<div id="card5">
<h4 class="y">Let me be your guide.</h4>
<h1>Here's what I've got:</h1>
<div id="a">
<h4 id="aa">Creativity</h4>
</div>
<div id="b">
<h4 id="bb">Know-how</h4>
</div>
<div id="c">
<h4 id="cc">Familiarity</h4>
</div>
</div>
<script type="text/javascript">
var aa = document.getElementById("aa");
var bb = document.getElementById("bb");
var cc = document.getElementById("cc");
var aamargin = style.aa.marginTop | 30;
var bbmargin = style.bb.marginTop | 30;
var ccmargin = style.cc.marginTop | 30;
var a = document.getElementById("a");
var b = document.getElementById("b");
var c = document.getElementsByTagName("c");
var aadown = true;
var bbdown = true;
var ccdown = true;
a.onmouseover = amove;
b.onmouseover = bmove;
c.onmouseover = cmove;
function amove() {
window.alert("Herro!");
if (aadown) {
aaup();
aadown = false;
}
}
function aaup() {
if (aamargin > 0) {
aamargin -= 1;
style.aa.marginTop = aamargin + "%";
requestAnimationFrame(aaup);
}
}
</script>
And when I mouse over the first div ("a"), of course, nothing happens. I put an alert box in to see if the amove() function was being triggered, and it wasn't. The alert never fired. No idea why. It's probably just a typo somewhere...
the error is here:
var aamargin = style.aa.marginTop | 30;
var bbmargin = style.bb.marginTop | 30;
var ccmargin = style.cc.marginTop | 30;
I think you mean aa.style instead of style.aa?
Two errors with style.aa.marginTop | 30;:
| is a bitwise operator, if you want logical OR, you need ||, like this: style.aa.marginTop || 30;
style is not defined, you need aa.style, like this: aa.style.marginTop || 30;
Last thing: bmove and cmove are not defined.
See the patched example here:
<div id="card5">
<h4 class="y">Let me be your guide.</h4>
<h1>Here's what I've got:</h1>
<div id="a">
<h4 id="aa">Creativity</h4>
</div>
<div id="b">
<h4 id="bb">Know-how</h4>
</div>
<div id="c">
<h4 id="cc">Familiarity</h4>
</div>
</div>
<script type="text/javascript">
var aa = document.getElementById("aa");
var bb = document.getElementById("bb");
var cc = document.getElementById("cc");
var aamargin = aa.style.marginTop || 30;
var bbmargin = bb.style.marginTop || 30;
var ccmargin = cc.style.marginTop || 30;
var a = document.getElementById("a");
var b = document.getElementById("b");
var c = document.getElementsByTagName("c");
var aadown = true;
var bbdown = true;
var ccdown = true;
bmove = cmove = amove; // just a quickfix
a.onmouseover = amove;
b.onmouseover = bmove;
c.onmouseover = cmove;
function amove() {
window.alert("Herro!");
if (aadown) {
aaup();
aadown = false;
}
}
function aaup() {
if (aamargin > 0) {
aamargin -= 1;
aa.style.marginTop = aamargin + "%";
requestAnimationFrame(aaup);
}
}
</script>

Categories

Resources