JS Calculating and constantly showing result - javascript

I have a starting value 1000.
On button FIGHT (which already has onclikc) it needs to do 1000-20 and shows in html 980, another click 960..
function damagec() {
var a = 500;
var b = a/20;
document.getElementById('resultl').innerHTML = b;
document.getElementById('resultl').style.color = 'green';
document.getElementById('resultlc').innerHTML = b;
document.getElementById('resultlc').style.color = 'green';
}
<div class="wall">
<p id="wallvalue">1000</p>
</div>
<button onclick="damagec()"><b>FIGHT</b></button>

window.damagec = function(){
var label = document.getElementById('wallvalue');
label.innerHTML = parseInt(label.innerHTML) - 20;
}
<div class="wall">
<p id="wallvalue">1000</p>
</div>
<BUTTON onclick="damagec()"><b>FIGHT</b></BUTTON>
You can store the value from the element and subtract whatever value you want from it before assigning it back to the element
var label = document.getElementById('wallvalue');
label.innerHTML = parseInt(label.innerHTML) - 20;

<div class="wall">
<p id="wallvalue">1000</p>
</div>
<BUTTON onclick="damagec()"><b>FIGHT</b></BUTTON>
<script>
function damagec(){
var wallVal = document.getElementById('wallvalue').innerHTML;
wallVal = wallVal - 20;
document.getElementById('wallvalue').innerHTML = wallVal;
}
</script>

Related

Manipulation of div elements with javascript

Can someone explain to me or figure it out. I dont know where I made a mistake here. I have javascript and html code where I get input from user for a flight. I want to make a counter to count all flights function counter() but it gives me the value of name. And another problem is I want when I click on the Accept button to make the background of the div element green function changeColor().
function addRow(){
var name = document.getElementById("name");
var plainNum = document.getElementById("plainNum");
var coordinates = document.getElementById("coordinates");
var radius = document.getElementById("radius");
var altitude = document.getElementById("altitude");
var type = document.getElementById("type");
if(!name.value || !plainNum.value || !coordinates.value || !radius.value || !altitude.value || !type.value){
alert("Enter all values");
return;
}
var output = document.getElementById("output");
var divForOutput = document.createElement("DIV");
var btn1 = document.createElement("BUTTON");
var btn2 = document.createElement("BUTTON");
var t1 = document.createTextNode("Accept");
var t2 = document.createTextNode("Reject");
btn1.appendChild(t1);
btn2.appendChild(t2);
divForOutput.innerHTML += name.value +", " + plainNum.value +"<br>" + "Radius: " + radius.value +", "+"Altitude: "+altitude.value+"<br>"+type.value+"<br>";
divForOutput.appendChild(btn1);
divForOutput.appendChild(btn2);
divForOutput.setAttribute('class','printing');
output.appendChild(divForOutput);
btn1.setAttribute('onclick','changeColor(this);');
btn2.setAttribute('onclick','disableButtons()');
// name.value = "";
// plainNum.value = "";
// coordinates.value = "";
// radius.value = "";
// altitude.value = "";
counter();
}
function disableButtons(){}
function changeColor(){
var parentofChild = document.getElementById("output");
output.div.background = green;
}
function counter(){;
var sum = document.getElementsByClassName("printing");
var counter = 0;
for(var i = 0;i <sum.length;i++){
counter+=parseInt(sum[i].innerHTML);
}
document.getElementById("total").innerHTML = counter;
}
<h1>Register flight</h1>
<form>
<div>
<label>Name and surname</label>
<input type="text" id="name">
</div>
<div>
<label>Number plate</label>
<input type="text" id="plainNum">
</div>
<div>
<label>Coordinates</label>
<input type="text" id="coordinates">
</div>
<div>
<label>Radius</label>
<input type="text" id="radius">
</div>
<div>
<label>Altitude</label>
<input type="text" id="altitude">
</div>
<div>
<label>Type</label>
<select id="type">
<option value="Comercial">Comercial</option>
<option value="Buissines">Buissines</option>
</select>
</div>
<div>
<input type="button" value="Submit" onclick="addRow();">
</div>
</form>
<divи>
<h3>Registered flights</h3>
<p>Total:<span id="total">0</span></p>
</div>
<div id="output">
</div>
Below I've fixed some of the code and made things a bit better.
function addRow(){
var name = document.getElementById("name");
var plainNum = document.getElementById("plainNum");
var coordinates = document.getElementById("coordinates");
var radius = document.getElementById("radius");
var altitude = document.getElementById("altitude");
var type = document.getElementById("type");
if(!name.value || !plainNum.value || !coordinates.value || !radius.value || !altitude.value || !type.value){
alert("Enter all values");
return;
}
var output = document.getElementById("output");
var divForOutput = document.createElement("DIV");
//var btn1 = document.createElement("BUTTON");
//var btn2 = document.createElement("BUTTON");
//var t1 = document.createTextNode("Accept");
//var t2 = document.createTextNode("Reject");
//btn1.appendChild(t1);
//btn2.appendChild(t2);
divForOutput.innerHTML = `
${name.value}<br>
Radius: ${radius.value}<br>
Altitude: ${altitude.value}<br>
${type.value}<br>
<button onclick="changeColor();">Accept</button>
<button onclick="disableButtons();">Reject</button>
`;
divForOutput.appendChild(btn1);
divForOutput.appendChild(btn2);
divForOutput.setAttribute('class','printing');
output.appendChild(divForOutput);
//btn1.setAttribute('onclick','changeColor(this);');
//btn2.setAttribute('onclick','disableButtons()');
// name.value = "";
// plainNum.value = "";
// coordinates.value = "";
// radius.value = "";
// altitude.value = "";
counter();
}
function disableButtons(){}
function changeColor(){
const output = document.getElementById("output");
output.style.backgroundColor = "green";
}
function counter(){;
const sum = document.getElementsByClassName("printing");
const counter = sum.getElementsByTagName('div').length;
return document.getElementById("total").innerHTML = counter;
}
There is an explanation for the background color here
As for the counter; what I did was count the div elements inside of the output div. That will give you the amount of flights a user has.
Your color setting had several problems. You don't use output.div.background to set the color, and you were using the undefined variable green instead of the string "green". This works:
function changeColor(){
var output = document.getElementById("output");
output.style.backgroundColor = 'green';
}
I don't know what you are trying to count with your counter function, so I can't fix that.

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>

if condition not running even when the condition satisfies

only the else statement in main.js statement where it reads scores-=1 runs and the if condition doesnt even when the condition satisfies. even after clicking on the right option my scores value doesnt increase by 1 instead it always decreasesby 1 which means it only satisfies the else statement
index.html
<div class="buttons">
<button id="button0"><span id="option0"></span></button>
<button id="button1"><span id="option1"></span></button>
<button id="button2"><span id="option2"></span></button>
<button id="button3"><span id="option3"></span></button>
</div>
main.js
var questions =[{
question:'abcbcb',
options:['a','b','c','d'],
answer:'b'
}, {
question:"capital of india",
options:['delhi','mum','pune','kol'],
answer:'delhi'
}]
var x = Math.floor(Math.random() * (questions.length));
var scores = 0;
function gameplay(){
var quesn = document.getElementById('question');
quesn.innerHTML =questions[x].question;
for(i=0;i<4;i++){
var opt = document.getElementById('option'+i);
opt.innerHTML = questions[x].options[i];
var score = document.getElementById('scores');
score.innerHTML = scores;
}
}
gameplay();
for(i=0;i<4;i++){
var y = document.getElementById('button'+i);
var z = document.getElementById('option'+i);
y.onclick = function(){
if((z.innerHTML) ==(questions[x].answer)){
scores +=1;
}
else{
scores -=1;
}
x=Math.floor(Math.random() * (questions.length));
gameplay();
}
}
For pure Javascript, use the innerHTML property.
For your example, use the following:
var spanVal = document.getElementById("option0").innerHTML;
var x = document.getElementById("option0").innerHTML;
console.log(x)
That is how you can attain the value, ".innerText" would also work.
(btw you labeled this as a question in java, this is javascript. Very different.
Hope this helps.
WORKING SAMPLE
Replace this
for(i=0;i<4;i++){
var y = document.getElementById('button'+i);
var z = document.getElementById('option'+i);
y.onclick = function(){
if((z.innerHTML) ==(questions[x].answer)){
scores +=1;
}
else{
scores -=1;
}
x=Math.floor(Math.random() * (questions.length));
gameplay();
}
}
With this
function answer(ans)
{
var myAnswer = document.getElementById('option'+ans);
if(myAnswer.innerHTML == (questions[x].answer))
{
scores += 1;
}
else{
scores -= 1;
}
x=Math.floor(Math.random() * (questions.length));
gameplay();
console.log(ans);
}
Then this
<p id="question"></p>
<div class="buttons">
<button id="button0"><span id="option0"></span></button>
<button id="button1"><span id="option1"></span></button>
<button id="button2"><span id="option2"></span></button>
<button id="button3"><span id="option3"></span></button>
</div>
<p id = 'scores'></p>
With this
<p id="question"></p>
<div class="buttons">
<button id="button0" onclick ="answer('0')"><span id="option0"></span></button>
<button id="button1" onclick ="answer('1')"><span id="option1"></span></button>
<button id="button2" onclick ="answer('2')"><span id="option2"></span></button>
<button id="button3" onclick ="answer('3')"><span id="option3"></span></button>
</div>
<p id = 'scores'></p>

Multiple progress bars visualy update only one

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.

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