Cannot get if-statement to work within function - javascript

I'm a complete JS noob who set off on a mission to create a quiz as a first/second-ish project. I suppose there are better ways to do this than the way I'm doing it, but currently I, after a correct submission of the user, want to remove the current iteration from the array which is converted into text through innerHTML, and do the same for the correct answer/explanation. This works well, up until the last bit. After the user completes the last question, it again removes the data from the array, showing "UNDEFINED" in the screen. I figured that, by adding an if statement to see if array.length > 1, I could circumvent this. I tried avoiding this by having a different if statement return true or false and then using && on the function; to no avail. Any and all if statements here give me the errors:
Uncaught ReferenceError: nextQuestion is not defined
at submitAnswer (VM588 script.js:61)
at HTMLButtonElement.onclick (quizpage.html:19)
I've attached the html and JS underneath.
var questionsOverview = ["1 - 1+1 = ?", "2 - What food do dieters tend to avoid?", "3 - Best fast food chain?"];
var answersOverview = ["[A] 1 [B] 3 [C] 2", "[A] Protein [B] Carbs [C] Glucose", "[A] Burger King [B] KFC [C] McDonalds"];
var answersLetter = ["C", "B", "C"];
var score = 0;
var answerUser = "test"
var currentQuestion = questionsOverview[0];
//set buttons as answersLetter
function setRed() {
document.getElementById(answerUser).style.background = "red";
}
function pressedA() {
answerUser = "A";
setRed();
document.getElementById("B").style.background = "";
document.getElementById("C").style.background = "";
};
function pressedB() {
answerUser = "B";
setRed();
document.getElementById("A").style.background = "";
document.getElementById("C").style.background = "";
};
function pressedC() {
answerUser = "C";
setRed();
document.getElementById("A").style.background = "";
document.getElementById("B").style.background = "";
};
//preps the first question/answer
function changeQuestion() {
document.getElementById("question").innerHTML = questionsOverview[0];
document.getElementById("answer").innerHTML = answersOverview[0];
};
//move to the next question
checkForEnd() && function nextQuestion() {
questionsOverview.shift();
answersOverview.shift();
answersLetter.shift();
changeQuestion();
};
// submit user answer
function submitAnswer() {
var audio = document.getElementById("tleeni");
audio.play();
if(answerUser === answersLetter[0]) {
alert("Correct! You're smart!");
nextQuestion();
}
else {
alert("Too bad!");
}
};
function checkForEnd() {
if (answersOverview.length > 1) {
return true;
} else {
return false;
}
};
<head>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="reset.css">
<script src="script.js" type="text/javascript"></script>
</head>
<body onload="changeQuestion()">
<div class="top-header" id="header">
<font color="white">Quiz</font></div>
<div class="main-content" id="main-content">
<h2 id="question">1</h2>
<h3 id="answer">2</h3>
<h4 id="score>">scorefiller</h4>
<div id="buttons">
<button onClick="pressedA()" class="answers" id="A">A</button>
<button onClick="pressedB()" class="answers" id="B">B</button>
<button onClick="pressedC()" class="answers" id="C">C</button>
</div>
<button onClick="submitAnswer()" id="submit">Submit answer!</button>
</div>
<audio id="tleeni" src="submit.mp3"></audio>
</body>
<style>
#import url('https://fonts.googleapis.com/css?family=Open+Sans|Pacifico');
</style>
Given that I'm really new to programming I'd appreciate any and all feedback. Thank you very much in advance!

I think your issue might be here
//move to the next question
checkForEnd() && function nextQuestion() {
questionsOverview.shift();
answersOverview.shift();
answersLetter.shift();
changeQuestion();
};
You're not actually calling the function nextQuestion; you're only making a boolean check that is equivalent to checkForEnd() && true since a function is a truthy value.
The function declaration is also "lost" hence why you're getting that reference error.
true && function burrito() {
return '🌯';
}
burrito();
// VM1158:1 Uncaught ReferenceError: burrito is not defined

checkForEnd() && function nextQuestion() {}
This doesn't run each time you click the button, nor does it run each time nextQuestion() is called. It does it once, whenever the code is first loaded. Even if it did all it would be doing is creating a named function expression, which is not useable outside the function itself, ie you can't call nextQuestion().
What you want is to use checkForEnd() inside the function and return based on that
function nextQuestion() {
if(!checkForEnd()) return;
questionsOverview.shift();
answersOverview.shift();
answersLetter.shift();
changeQuestion();
};

Related

Values from Array Only Change Upon First Run of a Function

I'm a beginner working on a trivia app, and I'm having a heck of a time getting the questions to iterate properly. I've tried things multiple different ways. Here is my current configuration.
The questions are iterated by the pullQuestions() function. This function pulls from an array called question.
The pullQuestions() function is run when the startbutton is clicked and when the submitA button is clicked. These buttons run either startGame() or submitA() respectively.
Please note, I have not yet implemented score tracking so the expectation of the submit button is currently limited to pulling the next question.
Question HTML
<div id="gameArea" class="questionbox" style="display: none;">
<div class="questionarea">
<h2 id="headerQ">Question Number</h2>
<p id="content">Question Text</p>
</div>
<div class="answerarea">
<!-- This can be ignored. This is where my options are but I'm not using them in my code yet -->
</div>
<button id="submitA" class="submitA" onClick="submitA()">Submit</button>
</div>
startGame() JavaScript (This works as expected)
function startGame(){
document.getElementById("startArea").style.display = "none";
document.getElementById("gameArea").style.display = "block";
question.id = 0;
pullQuestions();
console.log("startgame() Executed", question.id);
console.log(question[0], question[1]);
}
Question Array* (Set as a Global Variable)
function select1() {
if (op1.className == "selectionFalse") {
document.getElementById("op1").className = "selectionTrue";
document.getElementById("op2").className = "selectionFalse";
document.getElementById("op3").className = "selectionFalse";
document.getElementById("op4").className = "selectionFalse";
console.log("selected1()", "If Condition", op1.className);
}
else {
document.getElementById("op1").className = "selectionFalse";
}
}
submitA() JavaScript (Does not iterate through the Array but does increase the id attribute)
function submitA() {
question.id++;
console.log("submitA() Run)", "Question ID: ", question.id, headerQ, content);
}
*pullQuestions() JavaScript (This is run when the two above functions are run, but I only see results when it runs as part of the startGame() function.
function pullQuestions() {
if (question.id == 0) {
document.getElementById("headerQ").innerHTML = question[0].headerQ;
document.getElementById("content").innerHTML = question[0].content;
console.log("pullQuestions() Executed");
console.log("Variables: ", "headerQ = ", headerQ, "content = ", content);
}
if (question.id == 1) {
document.getElementById("headerQ").innerHTML = question[1].headerQ;
document.getElementById("content").innerHTML = question[1].content;
console.log("pullQuestions() Executed");
console.log("Variables: ", "headerQ = ", headerQ, "content = ", content);
}
if (question.id == 2) {
document.getElementById("headerQ").innerHTML = question[2].headerQ;
document.getElementById("content").innerHTML = question[2].content;
console.log("pullQuestions() Executed");
console.log("Variables: ", "headerQ = ", headerQ, "content = ", content);
}
}
I feel like I'm missing something small, but being that I'm new it's possible I'm approaching this all wrong. Any advice or direction is appreciated.
It doesn't work for you in the submitA button because you forgot to activate the call to in it pullQuestions
On the other hand, in startGame you did activate pullQuestions after you changed the id, so it works for you
This is what the function should look like
function submitA() {
question.id++;
pullQuestions();
console.log("submitA() Run)", "Question ID: ", question.id, headerQ, content);
}
I was able to get this to work. I added a variable to determine that the selection is "true." I also added a button to move to the next question so that the submit button / function is separate.

Why is if...else statement only compares single word values?

I am making a quiz app that will basically fetch the questions and answers from an API and display it to the webpage. It works fine, but the error handling isn't working. I have a if...else statement that will check if a user has selected the right answer, and if they did, play a sound and display "Nice job" to the user. If they did not, then tell the user that they need to try again. The behavior that I'm getting is very weird. Sometimes when I have chose the correct answer, it says it is not correct. It happens when there is spaces within the answer. For single words such as "true", "false" or "Hello" works fine. I logged the answer to the console stored in a variable called answer_container, when I logged it to the console, the answer and my choice are exactly the same. I have tried using === and == operators to see if that would work, but the result is the same. I have posted the full code including my HTML so that you can see what it is happening. Note it took me couple of tries to get the weird behavior to display.
Here is what I have tried:
var showAnswer = document.getElementById('showAnswer');
var button_score = document.getElementById('ShowScore');
var answer_container;
var url = 'https://opentdb.com/api.php?amount=1';
var score = 0;
var html_container = [];
async function fetchData() {
document.getElementById('next').disabled = true;
document.getElementById('msgSuccess').innerHTML = '';
document.getElementById('check').disabled = false;
document.getElementById('showAnswer').disabled = false;
var getData = await fetch(url);
var toJS = await getData.json();
answer_container = toJS.results[0].correct_answer;
var container = [];
for (var i = 0; i < toJS.results[0].incorrect_answers.length; i++) {
container.push(toJS.results[0].incorrect_answers[i]);
}
container.push(toJS.results[0].correct_answer);
container.sort(func);
function func(a, b) {
return 0.5 - Math.random();
}
html_container = [];
container.forEach(function(choices) {
html_container.push(`
<option value=${choices}>
${choices}
</option>
`)
});
document.getElementById('choice').innerHTML = html_container.join();
if (toJS.results[0].type === 'boolean') {
document.getElementById('type').innerHTML =
`This question is a ${toJS.results[0].category} question <br>
It is a true/false question<br>
Difficulty level: ${toJS.results[0].difficulty} <br>
Question: ${toJS.results[0].question}<br>
`;
} else {
document.getElementById('type').innerHTML =
`This question is a ${toJS.results[0].category} question <br>
It is a ${toJS.results[0].type} choice question <br>
Difficulty level: ${toJS.results[0].difficulty} <br>
Question: ${toJS.results[0].question}<br>
`;
}
}
fetchData();
showAnswer.addEventListener('click', function() {
document.getElementById('answer_element').innerHTML = "The answer to this question is " + answer_container;
document.getElementById('answer_element').style.display = "block";
setTimeout(function() {
document.getElementById('answer_element').style.display = "none";
}, 3000);
});
function check() {
var select_answer = document.getElementById('choice').value;
var audio = document.getElementById('audio');
if (select_answer == answer_container) {
score++;
document.getElementById('showAnswer').disabled = true;
document.getElementById('msgSuccess').innerHTML = "Nice job, keep going!";
document.getElementById('next').disabled = false;
document.getElementById('check').disabled = true;
audio.play();
console.log(answer_container);
}
if (select_answer != answer_container) {
score--;
document.getElementById('msgSuccess').innerHTML = "Keep trying, you will get it!";
document.getElementById('next').disabled = true;
console.log(answer_container);
}
}
<!DOCTYPE html>
<html>
<head>
<title>
Quiz App
</title>
</head>
<body>
<div id="type">
</div>
<label>
Select Your Answer...
</label>
<select id="choice">
</select>
<button id="showAnswer">
Show Answer
</button>
<p id="answer_element">
</p>
<button onclick="check()" id="check">
Check
</button>
<p id="msgSuccess">
</p>
<button id="next" onclick="fetchData()">
Next Question
</button>
<audio id="audio">
<source src="https://www.theharnishes.com/khanacademy.mp3" type="audio/mp3">
</audio>
</body>
</html>
You're using the expression select_answer == answer_container to determine if the choice is the correct answer.
select_answer comes from the value attribute of the option you've selected. However, when an answer value contains whitespace, HTML interprets only up to the first whitespace as the "value". When answers like North America come up, the option's value attribute is only North.
When generating your options in your HTML, you need to properly encapsulate them in double quotes ", like so:
html_container.push(`
<option value="${choices}">
${choices}
</option>
`)
Tangential, but it would probably be cleaner if you generated your elements with document.createElement() and Node.appendChild(); in this instance the quotes required to properly set the value attribute on each option would have been added for you.
Nice game!
The issue here is the text is getting truncated on whitespace in the HTML, so the value you're comparing it too doesn't match.
You need quotes in the HTML option to preserve white space.
<option value=${choices} <- picks the first word
<option value="${choices}" <- allows the whole string with spaces
var showAnswer = document.getElementById('showAnswer');
var button_score = document.getElementById('ShowScore');
var answer_container;
var url = 'https://opentdb.com/api.php?amount=1';
var score = 0;
var html_container = [];
async function fetchData() {
document.getElementById('next').disabled = true;
document.getElementById('msgSuccess').innerHTML = '';
document.getElementById('check').disabled = false;
document.getElementById('showAnswer').disabled = false;
var getData = await fetch(url);
var toJS = await getData.json();
console.log(toJS)
answer_container = toJS.results[0].correct_answer;
var container = [];
for (var i = 0; i < toJS.results[0].incorrect_answers.length; i++) {
container.push(toJS.results[0].incorrect_answers[i]);
}
container.push(toJS.results[0].correct_answer);
container.sort(func);
function func(a, b) {
return 0.5 - Math.random();
}
html_container = [];
container.forEach(function (choices) {
html_container.push(`
<option value="${choices}">
${choices}
</option>
`)
});
document.getElementById('choice').innerHTML = html_container.join();
if (toJS.results[0].type === 'boolean') {
document.getElementById('type').innerHTML =
`This question is a ${toJS.results[0].category} question <br>
It is a true/false question<br>
Difficulty level: ${toJS.results[0].difficulty} <br>
Question: ${toJS.results[0].question}<br>
`;
}
else {
document.getElementById('type').innerHTML =
`This question is a ${toJS.results[0].category} question <br>
It is a ${toJS.results[0].type} choice question <br>
Difficulty level: ${toJS.results[0].difficulty} <br>
Question: ${toJS.results[0].question}<br>
`;
}
}
fetchData();
showAnswer.addEventListener('click', function () {
document.getElementById('answer_element').innerHTML = "The answer to this question is " + answer_container;
document.getElementById('answer_element').style.display = "block";
setTimeout(function () {
document.getElementById('answer_element').style.display = "none";
}, 3000);
});
function check() {
var select_answer = document.getElementById('choice').value;
var audio = document.getElementById('audio');
console.log(select_answer, answer_container)
if (select_answer == answer_container) {
score++;
document.getElementById('showAnswer').disabled = true;
document.getElementById('msgSuccess').innerHTML = "Nice job, keep going!";
document.getElementById('next').disabled = false;
document.getElementById('check').disabled = true;
audio.play();
console.log(answer_container);
}
if (select_answer != answer_container) {
score--;
document.getElementById('msgSuccess').innerHTML = "Keep trying, you will get it!";
document.getElementById('next').disabled = true;
console.log(answer_container);
}
}
<!DOCTYPE html>
<html>
<head>
<title>
Quiz App
</title>
</head>
<body>
<div id="type">
</div>
<label>
Select Your Answer...
</label>
<select id="choice">
</select>
<button id="showAnswer">
Show Answer
</button>
<p id="answer_element">
</p>
<button onclick="check()" id="check">
Check
</button>
<p id="msgSuccess">
</p>
<button id="next" onclick="fetchData()">
Next Question
</button>
<audio id="audio">
<source src="https://www.theharnishes.com/khanacademy.mp3" type="audio/mp3">
</audio>
</body>
</html>

Multiple single onClick events

I'm just messing around on JavaScript. I want to create two single on-click buttons, each which serve separate functions. However, the first button's response is always that of the second if that group of code is in. It works fine independently.
I've double checked online and tried a few functions, but everything comes back to multiple-function buttons.
I'm not super advanced and I just do random programming for fun.
If the yes button is clicked, then "Good" should appear. If the no button is clicked, then "Bad" should appear.
When both groups of code are together, "Bad" is always shown, regardless of the button shown. If only the first group of code is isolated, then the result is "Good".
function myFunction() {
var str = "Good";
var result = str.link("https://www.allrecipes.com/search/results/?wt=authentic%20taco%20recipes&sort=re");
document.getElementById("happy").innerHTML = result;
}
</script>
<button onclick="myFunction()">No</button>
<p id="sad"></p>
<script>
function myFunction() {
var str = "Bad";
var result = str.link("https://www.tacobell.com/");
document.getElementById("sad").innerHTML = result;
}
Do you like tacos?
<br />
<button onclick="myFunction()">Yes</button>
<p id="happy"></p>
You can also use a single click event function for both of your buttons.
See below code -
function myFunction(elem) {
var btnHtml = elem.innerHTML;
var str = "Good";
var id = "happy"
if(btnHtml == "No"){
str = "Bad";
id = "sad";
}
var result = str.link("https://www.allrecipes.com/search/results/?wt=authentic%20taco%20recipes&sort=re");
document.getElementById(id).innerHTML = result;
}
Do you like tacos?
<br />
<button onclick="myFunction(this)">Yes</button>
<p id="happy"></p>
<button onclick="myFunction(this)">No</button>
<p id="sad"></p>
You can do something like this, one function for both onclick events.
HTML
<p>Click the button to trigger a function.</p>
<button onclick="myFunction('yes')">Yes</button>
<button onclick="myFunction('no')">No</button>
<p id="demo"></p>
Javascript
function myFunction(value)
{
document.getElementById("demo").innerHTML=value;
}
Here's the fiddle
http://jsfiddle.net/840Larsn/
It is because you are using Function constructor and the functions are created in the global scope and therefore the second function overwrites the first one.
You can refer to here to see the definition.
You can use jquery if you wish,its simple
$('.clickbtn').click(function(e){
var str,result ;
var data = $(this)
if(data.attr('data-id')==1)
{
str = "Good";
result = str.link("https://www.allrecipes.com/search/results/?wt=authentic%20taco%20recipes&sort=re");
$("#text").html(result)
}
else
{
str = "Bad";
result = str.link("https://www.tacobell.com/");
$("#text").html(result)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Do you like tacos?
<br />
<button class="clickbtn" data-id=1>Yes</button>
<button class="clickbtn" data-id=2>No</button>
<p id="text"></p>
You should name your function differently:
In fact when you declare the second function in your original code it overwrites the first one because they have the same name.
function myGoodFunction() {
var str = "Good";
var result = str.link("https://www.allrecipes.com/search/results/?wt=authentic%20taco%20recipes&sort=re");
document.getElementById("happy").innerHTML = result;
}
function myBadFunction() {
var str = "Bad";
var result = str.link("https://www.tacobell.com/");
document.getElementById("sad").innerHTML = result;
}
Do you like tacos?
<br />
<button onclick="myGoodFunction()">Yes</button>
<p id="happy"></p>
<button onclick="myBadFunction()">No</button>
<p id="sad"></p>

Javascript save , erase and reload input value

I have a problem with my Script. I want to do the following steps in this order:
1. Save the text in the input field.
2. Delete all text in the input field.
3. Reload the same text that was deleted before in the input field.
The problem with my script is that the ug()- function writes undefined in my textbox instead of the string that should be stored in var exput. The alert(exput) however shows me the correct content.
Help would be very much appreciated. And I'm sure there is better ways to do that, I'm quite new to this stuff.
HTML
<textarea id="a" style="width: 320px; height: 200px;"></textarea>
<input type="checkbox" id="remember" onclick="merker();deleter();ug()" />
Javascript
function merker() {
var merkzeug = document.getElementById('a').value;
ug(merkzeug);
};
function deleter() {
if(document.getElementById('remember').checked == true)
{
document.getElementById('a').value = "";
}
else {document.getElementById('a').value = "";
}
};
function ug(exput) {
alert(exput);
document.getElementById('a').value = exput;
};
Your code is calling merker(); deleter(); ug(); in the onclick event, but ug() is already called by merker(). You should be doing this instead:
function merker() {
var merkzeug = document.getElementById('a').value;
deleter();
ug(merkzeug);
};
function deleter() {
if(document.getElementById('remember').checked == true)
{
document.getElementById('a').value = "";
}
else {document.getElementById('a').value = "";
}
};
function ug(exput) {
alert(exput);
document.getElementById('a').value = exput;
};
<textarea id="a" style="width: 320px; height: 200px;"></textarea>
<input type="checkbox" id="remember" onclick="merker();" />
I changed Your Javascript:
function merker() {
merkzeug = document.getElementById('a').value;//global variable without var
ug();//why You use it here? I think only for test. So delete it after.
};
function deleter() {
if(document.getElementById('remember').checked == true)
{
document.getElementById('a').value = "";
}
else {document.getElementById('a').value = "";
}
};
function ug() {
alert(merkzeug);
document.getElementById('a').value =merkzeug;
};
Problems with your code:
method ug was used with argument and without argument ( i changed to without )
to restore deleted value it must be saved to some variable, i saved to global merkzeug variable - this is not good practice but sufficient in this case
next i used merkzeug to restore value in textarea in ug() function
i do not know why You using ug() two times? maybe delete one of them is good thing to do.
In plunker - https://plnkr.co/edit/fc6iJBL80KcNSpaBd0s9?p=info
problem is: you pass undefined variable in the last ug function:
you do: merker(value) -> ug(value); delete(); ug(/*nothing*/);
or you set your merkzeung variable global or it will never be re-inserted in your imput:
var merkzeug = null;
function merker() {
merkzeug = document.getElementById('a').value;
ug(merkzeug);
};
function deleter() {
if(document.getElementById('remember').checked == true)
{
document.getElementById('a').value = "";
}
else {document.getElementById('a').value = "";
}
};
function ug(exput) {
if (typeof exput === 'undefined') exput = merkzeung;
alert(exput);
document.getElementById('a').value = exput;
};

How to loop same javascript code for more than one div elements?

I have made three "boxes" and each box contains a button. When I click the button, box hiding, when click again, box appears.
This is my html code:
<div id="SC1_A_"> <!-- BOX -->
<div id="SC1_B_" onClick="SC1();" class="something"> </div> <!-- BUTTON -->
</div>
<div id="SC2_A_">
<div id="SC2_B_" onClick="SC2();" class="something"> </div>
</div>
<div id="SC3_A_">
<div id="SC3_B_" onClick="SC3();" class="something"> </div>
</div>
This is my javascript code:
<script type="text/javascript">
function SC1(){
var SC1_A = document.getElementById('SC1_A_);
var SC1_B = document.getElementById('SC1_B_);
if (SC1_A.style.display == 'block' || SC1_A.style.display == ''){
SC1_A.className = 'something';
SC1_B.className = 'something else';}
else {SC1_A.className = 'something else';
SC1_B.className = 'something';}
}
}
</script>
The example above works, but I have to make three similar scripts for each button. So I though to make something like this script below, using for loop. As you can imagine it didn't work. Any idea how can I make it work???
<script type="text/javascript">
for (i=1; i<10; i++){
function SCi(){
var SCi_A = document.getElementById('SC'+i+'_A_');
var SCi_B = document.getElementById('SC'+i+'_B_');
if (SCi_A.style.display == 'block' || SCi_A.style.display == ''){
SCi_A.className = 'something';
SCi_B.className = 'something else';}
else {SCi_A.className = 'something else';
SCi_B.className = 'something';}
}
}
</script>
Please don't down-vote if you think question is too easy, but just give me your help here!!! Thank you in advance!!!
You're on the right track, you just need to learn the right syntax for what you are trying to express:
var SC = [];
First off, to have a lot of different functions, so instead of attempting to name them differently (which you were trying to do), we are going to just store each function in a different index in the SC array.
for (var i = 1; i < 10; i++) {
SC[i] = (function () {
var SC_A = document.getElementById('SC' + i + '_A_');
var SC_B = document.getElementById('SC' + i + '_B_');
return function () {
if (SC_A.style.display === 'block' || SC_A.style.display === '') {
SC_A.className = 'something';
SC_B.className = 'something else';
} else {
SC_A.className = 'something else';
SC_B.className = 'something';
}
}
})();
}
Now, to call these functions you would do SC[1](), SC[2](), ... So you can either put that in each onclick in your HTML, or you could bind the events from the javascript.
Edit: I forgot to mention this because it isn't directly related to the syntax of the code, but the calls to 'document.getElementByIdwill not work until the document is fully loaded. So if you just put the script directly between to` tags it won't work. You have two choices. You either can keep the current code, but run it when the page loads. Or, you could restructure the code like this:
var SC = [];
for (var i = 1; i < 10; i++) {
SC[i] = (function (i) {
return function () {
var SC_A = document.getElementById('SC' + i + '_A_');
var SC_B = document.getElementById('SC' + i + '_B_');
if (SC_A.style.display === 'block' || SC_A.style.display === '') {
SC_A.className = 'something';
SC_B.className = 'something else';
} else {
SC_A.className = 'something else';
SC_B.className = 'something';
}
}
})(i);
}
What's happening here is you are calling document.getElementById every time the button is clicked, instead of just once when the function is created. Slightly less efficient, but it works.
You define each section on the page as calling the one function and passing in the name of the other .
<div id="SC1_A_"> <!-- BOX -->
<div id="SC1_B_" onClick="SC('SC1_A_');" class="something"> </div> <!-- BUTTON -->
</div>
<div id="SC2_A_">
<div id="SC2_B_" onClick="SC('SC2_A_');" class="something"> </div>
</div>
<div id="SC3_A_">
<div id="SC3_B_" onClick="SC('SC3_A_');" class="something"> </div>
</div>
There is just one function used for all of them
function SC(nameOfA){
var SCi_A = document.getElementById(nameOfA);
var SCi_B = this;
if (SCi_A.style.display == 'block' || SCi_A.style.display == ''){
SCi_A.className = 'something';
SCi_B.className = 'something else';
} else {
SCi_A.className = 'something else';
SCi_B.className = 'something';}
}
}
here you can use this function on every click:
<div id="SC1_A_"> <!-- BOX -->
<div id="SC1_B_" onClick="SC(event)" class="something"> </div> <!-- BUTTON -->
</div>
<script type="text/javascript">
function SC(event){
var SCA = event.currentTarget.parentNode;
var SCB = event.currentTarget;
................
}
</script>
Your code is defining a function named SCi 8 times. I think if you swap the first two lines you will get what you want.
You're redefining the same function (function SCi) eight times. The only version of the function that is retained is the version that's defined last. Going by your code, you're only creating a function that can work with the 8th box.

Categories

Resources