JavaScript Not Triggering - javascript

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>

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:

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>

JS Calculating and constantly showing result

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>

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.

Dynamically changing pictures based on text input

I am writing a webpage at the moment where I am converting temperature to Fahrenheit from Celsius and vice versa. While doing that if the temperature is in a certain degree I need to display a picture and if it is in a different range I need to display another picture(and one more time). I have got the right picture displaying at the right time, but I can't seem to figure out how to get the pictures to switch, and instead they just continually add up.
<!DOCTYPE html>
<html>
<head>
<script>
function convertTemp(fAfter)
{
var c = document.getElementById('c'), f = document.getElementById('f');
var fAfter;
var cAfter
if(c.value != '')
{
f.value = (c.value * 9 / 5 + 32);
fAfter = (c.value * 9 / 5 + 32);
c.value = c.value;
return fAfter;
}
else
{
c.value = ((f.value - 32) * 5 / 9);
f.value = f.value;
fAfter = f.value;
return fAfter;
}
}
function changePicture()
{
var A = convertTemp();
if (A > 50)
{
var img = document.createElement('img');
img.src = "warm.gif";
document.body.appendChild(img);
}
else if (A < 50 & A > 32)
{
var img = document.createElement('img');
img.src = "cool.gif";
document.body.appendChild(img);
}
else
{
var img = document.createElement('img');
img.src = "cold.gif";
document.body.appendChild(img);
}
}
function clearBoth()
{
var c = document.getElementById('c');
c.value = '';
var f =document.getElementById('f');
f.value= '';
}
var button = document.getElementById("convert");
</script>
</head>
<body>
<input placeholder = "Celsius" id="c" onclick='clearBoth()' >&#176C</br>
<input placeholder = "Fahrenheit" id="f" onclick='clearBoth()' >&#176F</br>
<button type="button" id="convert" onclick="convertTemp() & changePicture()">Convert</button>
</body>
<p>
</p>
</html>
You can create an img that is available on the global scope and change it's src attribute according to the input value. Initially you can hide the image.
HTML :
<body>
<input placeholder = "Celsius" id="c" onclick='clearBoth()' >&#176C</br>
<input placeholder = "Fahrenheit" id="f" onclick='clearBoth()' >&#176F</br>
<img src="" id="tempImage"/>
<button type="button" id="convert">Convert</button>
</body>
javaScript :
var img = document.getElementById("tempImage");
img.style.display = 'none';
function convertTemp(fAfter)
{
var c = document.getElementById('c'), f = document.getElementById('f');
var fAfter;
var cAfter
if(c.value != '')
{
f.value = (c.value * 9 / 5 + 32);
fAfter = (c.value * 9 / 5 + 32);
c.value = c.value;
return fAfter;
}
else
{
c.value = ((f.value - 32) * 5 / 9);
f.value = f.value;
fAfter = f.value;
return fAfter;
}
}
function changePicture()
{
var A = convertTemp();
img.style.display = '';
if (A > 50)
{
img.src = "http://3.bp.blogspot.com/-I5le-iONsuc/UDwY0gx6LMI/AAAAAAAAAnk/2VVq3KX7e2I/s1600/600px-Capital_C.png";
}
else if (A < 50 & A > 32)
{
img.src = "http://static.tumblr.com/148af423ee41cdb24507f372f95bd4d0/wuvn5qh/ovFmzk9sh/tumblr_static_f-word-1ha91xq.png";
}
else
{
img.src = "http://static.tumblr.com/148af423ee41cdb24507f372f95bd4d0/wuvn5qh/ovFmzk9sh/tumblr_static_f-word-1ha91xq.png";
}
}
function clearBoth()
{
var c = document.getElementById('c');
c.value = '';
var f =document.getElementById('f');
f.value= '';
}
var button = document.getElementById("convert");
button.onclick = changePicture;
jsFiddle

Categories

Resources