Javascript: Loop items in array - javascript

For my website I need a function with questions and answers in loop.
After the last question the first question should come again.
I have found something but the loop does not work, it is certainly simple but I do not get that.
<!DOCTYPE html>
<html>
<body>
<div>
<div id="question" onclick="changeText()">
Start Quiz
</div>
<div id="answer" onclick="nextQuestion()">
are you ready?
</div>
</div>
<script type="text/javascript">
var details = "Question 1ans:Answer 1qst:Question 2ans:Answer 2qst:Question 3ans:Answer 3qst:Question 4ans:Answer 4qst:Question 5ans:Answer 5qst:Question 6ans:Answer 6qst:Question 7ans:Answer 7qst:Question 8ans:Answer 8qst:Question 9ans:Answer 9qst:Question 10ans:Answer 10";
var questionList = details.split("qst:");
var div = document.getElementById('question');
var ans = document.getElementById('answer');
function changeText(){
if (div.style.display !== 'none') {
div.style.display = 'none';
ans.style.display = 'block';
}
else {
div.style.display = 'block';
ans.style.display = 'none';
}
}
function nextQuestion(){
div.style.display = 'block';
ans.style.display = 'none';
var max = questionList.length;
if(max > 0){
var num = 0;
var qst = questionList[num].split("ans:");
div.innerHTML =qst[0];
ans.innerHTML = qst[1];
questionList.splice(num,1);}
else {
}
}
</script>
</body>
</html>

You must reset value of n every time reach to max so you must put n in outer scope in global variable scope and don't splice questionList because you want to iterate over that array again after reaching to end of it:
var details = "Question 1ans:Answer 1qst:Question 2ans:Answer 2qst:Question 3ans:Answer 3qst:Question 4ans:Answer 4qst:Question 5ans:Answer 5qst:Question 6ans:Answer 6qst:Question 7ans:Answer 7qst:Question 8ans:Answer 8qst:Question 9ans:Answer 9qst:Question 10ans:Answer 10";
var questionList = details.split("qst:");
var div = document.getElementById('question');
var ans = document.getElementById('answer');
//Variable n must declare here
var num = 0;
function changeText() {
if (div.style.display !== 'none') {
div.style.display = 'none';
ans.style.display = 'block';
} else {
div.style.display = 'block';
ans.style.display = 'none';
}
}
function nextQuestion() {
div.style.display = 'block';
ans.style.display = 'none';
var max = questionList.length;
if (max > 0) {
var qst = questionList[num].split("ans:");
div.innerHTML = qst[0];
ans.innerHTML = qst[1];
//there is no need to splice questionList
//questionList.splice(num, 1);
num++;
//Check for num to not to be greater than questionList.length
if (num >= max)
num = 0;
} else {
}
}
<div id="question" onclick="changeText()">
Start Quiz
</div>
<div id="answer" onclick="nextQuestion()">
are you ready?
</div>

Related

How to get all the ids of the elements where the condition is true?

I'm trying to make a toggling function with js to hide all comments with its children.
this is a comment in html:
<div>
<a onclick="return toggle(4 /*id*/, 7 /*lft*/, 10 /*rgt*/)" href="javascript:void(0)">[-]</a>
<div id="com4" class="md" value="7-10">yellow</div>
</div>
⬆ this comment has a child value="8-9", I want to hide the comment with id="com4" and it child.--> this is the question how to find the id where the comments where it value="8-9"
and this is my js:
function toggle(id, lft, rgt) {
var kids = (rgt - lft - 1) / 2;
if (kids >= 1) {
var element = document.querySelectorAll("div.md").getAttribute('value');
var low = Number(element.split('-')[0]);
var high = Number(element.split('-')[1]);
if (low > lft && high < rgt) {
var x = //get the ids of these elements where: low>lft && high<rgt
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
} else {
var x = document.getElementById("com" + id);
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
return false;
}
I'm trying to find all ids of the children ⬆:
if (low > lft && high < rgt) {
var x = //get the ids of these elements where: low>lft && high<rgt
here's an image to understand how my comment system works:
nested sets
thanks in advance, and I'm sorry for my bad english ;)
Please take a look at these codes:
function toggle(id, lft, rgt) {
var kids = (rgt - lft - 1) / 2;
if (kids >= 1) {
var element = document.querySelectorAll("div.md#com" + id)[0].getAttribute('value');
var low = Number(element.split('-')[0]);
var high = Number(element.split('-')[1]);
for(var i = low + 1; i <= high - 1; i += 1){
var x = document.querySelectorAll("div.md#com" + i)[0]
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
}
}
<div>
<div id="com4" class="md" value="7-10">yellow
<a onclick="toggle(4, 7, 10)" href="javascript:void(0)">[-]</a>
</div>
<div id="com5" class="md">Should not collapse</div>
<div id="com8" class="md">Should collapse</div>
<div id="com9" class="md">Should collapse</div>
<div id="com11" class="md">Should not collapse</div>
</div>

why wont my else if statements work

Hello everyone i am not really sure why my else if statements aren't working as i intend to have them run on the click of a button and each else if question run until one of them is true and returns the 'correct' or 'wrong' boxes. Are my else if statements even being called on correctly? And if so am i referring to the 'correctAnswer' correctly? Thanks in advance!:)(oh and by the way the display style of the 'wrong' and 'correct' divs are set to 'none' in an external css stylesheet)
The Javascript:
var gameOn = false;
var score;
var interval;
Array.prototype.shuffle = function(){
var i = this.length, j, temp;
while(--i > 0){
j = Math.floor(Math.random() * (i+1));
temp = this[j];
this[j] = this[i];
this[i] = temp;
}//while loop bracket
return this;
}
function stopGame() {
gameOn = false;
if (interval) {
clearInterval(interval);
interval = null;
}//if interval bracket
document.getElementById("startreset").innerHTML = "Start Game";
document.getElementById("time-remaining").style.display = "";
}//function stopGame bracket
//if we click on the start/reset
document.getElementById("startreset").onclick = function () {
//if we are not playing
if (gameOn) {
stopGame();
}/*if gameOn bracket*/ else {
//change mode to playing
gameOn = true;
//set score to 0
score = 0;
document.getElementById("scorevalue").innerHTML = score;
//show countdown box
document.getElementById("time-remaining").style.display = "block";
document.getElementById("startreset").innerHTML = "Reset Game";
var counter = 60;
//reduce time by 1sec in loops
interval = setInterval(timeIt, 1000);
function timeIt(){
document.getElementById("timer-down").innerHTML = counter;
counter--;
//timeleft?
//no->gameover
if ( counter === 0) {
stopGame();
document.getElementById("game-over").style.display = "block";
document.getElementById("game-over").innerHTML = "Game Over" + "<br />" + "<br />" + "Your Score is " + score + "!";
}//if counter bracket
}//timeIt function bracket
//generate new Q&A
generateQA();
function generateQA(){
//this is the first number in the equation
var Na = 1+ Math.round(Math.random() * 9);
//this is the second number in the equation
var Nb = 1+ Math.round(Math.random() * 9);
//the correct answer is when you multiply both together
correctAnswer = Na * Nb;
//these are the randomly generated wrong answers
var w1 = 1+ Math.round(Math.random() * 16);
var w3 = 1+ Math.round(Math.random() * 22);
var w4 = 1+ Math.round(Math.random() * 92);
document.getElementById("question").innerHTML = Na + "x" + Nb;
console.log(correctAnswer);
var myArray = [w1, correctAnswer, w3, w4];
var result = myArray.shuffle();
document.getElementById("box1").innerHTML = result[0];
document.getElementById("box2").innerHTML = result[1];
document.getElementById("box3").innerHTML = result[2];
document.getElementById("box4").innerHTML = result[3];
}//generateQA function bracket
function evaluateAnswer(){
var a = document.getElementById("correct");
var b = document.getElementById("wrong");
if ('box1' === correctAnswer){
a.style.diplay = 'block';
generateQA();
}else if('box1' !== correctAnswer){
b.style.diplay = 'block';
}else if('box2' === correctAnswer){
a.style.diplay = 'block';
generateQA();
}else if('box2' !== correctAnswer){
b.style.diplay = 'block';
}else if('box3' === correctAnswer){
a.style.diplay = 'block';
generateQA();
}else if('box3' !== correctAnswer){
b.style.diplay = 'block';
}else if('box4' === correctAnswer){
a.style.diplay = 'block';
generateQA();
}else if('box4' !== correctAnswer){
b.style.diplay = 'block';
}
}//evaluateAnswer function bracket
}//else statement bracket
}//startreset button function bracket
The HTML:
<div id="correct">
Correct!
</div>
<div id="wrong">
Try Again
</div>
<div id="question">
<span id="firstInt"></span><span id="secondInt"></span>
</div>
<div id="instruction">
Click on the Correct Answer
</div>
<div id="choices">
<div id="box1" onclick = "evaluateAnswer()" class="boxes"></div>
<div id="box2" onclick = "evaluateAnswer()" class="boxes"></div>
<div id="box3" onclick = "evaluateAnswer()" class="boxes"></div>
<div id="box4" onclick = "evaluateAnswer()" class="boxes"></div>
</div>
<div id="startreset">
Start Game
</div>
Beyond the comments to your question your logic is broken.
if ('box1' === correctAnswer()){
a.style.diplay = 'block';
generateQA();
}else if('box1' !== correctAnswer()){
b.style.diplay = 'block';
}
Your first if and second if are mutually exclusive which means that one of those two will always be true. All of the other else operations will not execute.
UPDATE - Includes changes based on your latest comment.
Since you are just trying to indicate if the answer is right or not then try something like this:
You would need to move the location of result to global:
var result = [];
With result being a global variable then you could change the rest of your code to be something like this:
function evaluateAnswer(box){
var a = document.getElementById("correct");
var b = document.getElementById("wrong");
if (result[box] === correctAnswer) {
a.style.diplay = 'block';
b.style.diplay = 'none';
generateQA();
} else {
a.style.diplay = 'none';
b.style.diplay = 'block';
}
}//evaluateAnswer function bracket
<div id="correct">Correct!</div>
<div id="wrong">Try Again</div>
<div id="question">
<span id="firstInt"></span>
<span id="secondInt"></span>
</div>
<div id="instruction">
Click on the Correct Answer
</div>
<div id="choices">
<div id="box1" onclick="evaluateAnswer(0)" class="boxes"></div>
<div id="box2" onclick="evaluateAnswer(1)" class="boxes"></div>
<div id="box3" onclick="evaluateAnswer(2)" class="boxes"></div>
<div id="box4" onclick="evaluateAnswer(3)" class="boxes"></div>
</div>
<div id="startreset">
Start Game
</div>
This line:
if (result[box] === correctAnswer) {
would test to see if the correct box was clicked on.
This is the changed HTML:
<div id="box1" onclick="evaluateAnswer(0)" class="boxes"></div>
<div id="box2" onclick="evaluateAnswer(1)" class="boxes"></div>
<div id="box3" onclick="evaluateAnswer(2)" class="boxes"></div>
<div id="box4" onclick="evaluateAnswer(3)" class="boxes"></div>
When the user clicks on the various boxes the onClick handler calls the evaluateAnswer function and passes in the index of the box was clicked on. The 0 to 3 indicate the box number and also the index of answer stored in the result array. 0 is results[0], 1 is results[1], etc.
Since you would be storing the answers in the results array, then you only need to coordinate between what the user clicks on and what the answer is for that box. If they click on box 1 then evaluateAnswer(0) is called. That function uses the 0 to look up the answer in results[0]. If that is the correct answer then you shows the correct message. Otherwise it shows the wrong message.
I don't if this helps you but I renamed some of your functions because they didn't make sense. Also if your going to name a lot of variables up top your better off doing like below. Also your missing the ending div for your correct div. Better to use an ternary operator if your doing a simple if/else statement.
var gameOn = false,
score,
interval,
startBtn = document.getElementById('startReset'),
timer = document.getElementById("time-remaining");
Array.prototype.shuffle = function(){
var i = this.length, j, temp;
while(--i > 0){
j = Math.floor(Math.random() * (i+1));
temp = this[j];
this[j] = this[i];
this[i] = temp;
}//while loop bracket
return this;
}
function stopGame() {
gameOn = false;
startBtn.innerHTML = "Start Game";
// timer.style.display = "none";
// marked out will throw error not on html
}
function startGame() {
gameOn = true;
startBtn.innerHTML = 'Stop Game';
}
function checkGameStatus() {
console.log(gameOn)
gameOn ? stopGame() : startGame();
}
startBtn.addEventListener('click', checkGameStatus);

Toggling between blocks

Why is this code not working and how to solve the one block is shown and some block is hide?
function vsd(){
var asd = document.getElementById("asd");
var vsd = document.getElementById("vsd");
var psd = document.getElementById("psd");
var vps = document.getElementById("vps");
var asp = document.getElementById("asp");
var vsp = document.getElementById("vsp");
var sad = document.getElementById("sad");
if (vsd.style.display === "none") {
vsd.style.display ="block";
asd.style.display = "none";
psd.style.display = "none";
vps.style.display = "none";
asp.style.display = "none";
vsp.style.display = "none";
sad.style.display = "none";
} else {
vsd.style.display = "none";}
}
Be sure that vsd is in display:none mode at load time and in the else statement think to show back psd, vsd blah
I have replaced your approach with a css class hide
window.onload = vsd();
function vsd(){
var asd = document.getElementById("asd");
var vsd = document.getElementById("vsd");
var psd = document.getElementById("psd");
var vps = document.getElementById("vps");
var asp = document.getElementById("asp");
var vsp = document.getElementById("vsp");
var sad = document.getElementById("sad");
console.log($("#vsd")[0].attr('style'))
if (vsd.classList.contains("hide") {
vsd.classList -= "hide";
asd.classList += "hide";
psd.classList += "hide";
vps.classList += "hide";
asp.classList += "hide";
vsp.classList += "hide";
sad.classList += "hide";
} else {
vsd.classList += "hide";
}
}
.hide {
display : none;
}
<button id="vsd" class="">vsd</button>
<button id="asd" class="hide">asd</button>
<button id="psd" class="hide">psd</button>
<button id="vps" class="hide">vps</button>
<button id="asp" class="hide">asp</button>
<button id="vsp" class="hide">vsp</button>
<button id="sad" class="hide">sad</button>

Javascript for loop not repeating strings

very new to Javascript here, and I think I'm having a logic issue. So basically for class I'm building a hangman game, and I am having trouble with double letters. for instance if the word is food, when I enter an "O" it will pass through the for loop, hit that first O, push it to the screen, and stop dead in its tracks. I can do whatever I want to that first "O" but a second one or any other repeated letter gets ignored. Now the alert I wrote directly under the start of the for() loop, will successfully print both "O's", as will logging it to the console, or even flat out writing document.write(splitWord[m]);
So to me, I think it has to be my if statement. I could be 100% wrong on this, but I assume that the if statement tells it to see the first "O", do what's in the bracket, and then move on to the next letter skipping any doubles. If I am right about this, what would be a better option to keep the loop going, so both "O's" would be filled. And if I am completely wrong, what would be a better course of action to accomplish this task. Any help would be very greatly appreciated.
Thanks
var remainingLetters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
var removedLetters =[];
var wordList = ["django", "the#good#the#bad#and#the#ugly", "a#fistful#of#dollars","for#a#few#dollars#more","once#upon#a#time#in#the#west","the#wild#bunch","pale#rider"];
var titleList =["django", "The Good The Bad And The Ugly", "A Fistful of Dollars", "For a few Dollars More", "Once Upon a Time in the West", "The Wild Bunch", "Pale Rider"];
var songList =["Jango", "The Good The Bad And The Ugly", "Fistful of Dollars", "For a few Dollars More", "Once Upon a Time in the West", "The Wild Bunch", "Pale Rider"]
var selectedWord;
console.log(selectedWord);
var livesRemaining = 12;
var score = 0;
var wordWorth = 0;
var wins = 0;
var losses = 0;
var gameOn = false;
function chooseAWord(){
selectedWord = wordList[Math.floor(Math.random() * wordList.length)];
console.log(selectedWord);
}
function printWord(){
document.getElementById("wordDisplayer").innerHTML = selectedWord;
}
function buildTiles(){
// create a new div element
// and give it some content
var splitWord = selectedWord.split("");
for(i = 0; i < splitWord.length; i++){
if (splitWord[i] != '#'){
// var newTile = document.createElement("div");
//var newContent = document.createTextNode("");
//newTile.appendChild(newContent); //add the text node to the newly created div.
document.getElementById("wordTiles").innerHTML += '<div class="tileStyle" id="' + splitWord[i] + '"></div>';
wordWorth++;
// add the newly created element and its content into the DOM
//var currentDiv = document.getElementById("wordTiles");
//currentDiv.appendChild(newTile, currentDiv);
// newTile.setAttribute("class", "tileStyle");
}else if(splitWord[i] == '#'){
var blankTile = document.createElement("div");
var spaceContent = document.createTextNode("");
blankTile.appendChild(spaceContent);
document.getElementById("wordTiles").innerHTML += '<div class="blankStyle" id="' + splitWord[i] + '"></div>';
}
}
}
function clearTiles(){
var myNode = document.getElementById("wordTiles");
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
}
function refreshAlphabet(){
remainingLetters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
displayAvailableLetters();
}
function keyPressed(){
checkPlayerChoiceNew();
}
var playerGuess = document.onkeyup = function myKeyDown(event){
playerGuess = event.key;
if(gameOn==true){
keyPressed();
}else{
}
}
function checkPlayerGuess(){
document.getElementById("isThisWorking").innerHTML = playerGuess;
}
// function myFunction() {
// var str = "Tha bast things in lifa ara free";
// var patt = new RegExp(playerGuess);
// var res = patt.test(selectedWord.toLowerCase());
// document.getElementById("demo").innerHTML = res;
//}
function displayAvailableLetters(){
document.getElementById("lettersStillAvailable").innerHTML = remainingLetters;
console.log(remainingLetters);
}
function displayRemovedLetters(){
document.getElementById("lettersUsed").innerHTML = removedLetters;
}
function updateScore(){
document.getElementById("scoreTotal").innerHTML = score;
}
function updateWins(){
document.getElementById("winTotals").innerHTML = wins;
}
function updateLosses(){
document.getElementById("lossTotals").innerHTML = losses;
}
function checkScore(){
if(score == selectedWord.length && livesRemaining > 0){
document.getElementById("gameOver").innerHTML = "WINNER! Congratulations!!!";
wins++;
updateWins();
gameOn=false;
}else if (livesRemaining == 0){
livesRemaining == -1;
document.getElementById("gameOver").innerHTML = "You have failed!";
losses++;
updateLosses();
gameOn=false;
}else{
document.getElementById("gameOver").innerHTML = "Good Luck!";
}
}
function checkPlayerChoiceNew(){
var splitWord = selectedWord.split("");
var choice = new RegExp(playerGuess);
var compareWord = choice.test(selectedWord.toLowerCase());
var compareAlphabet = choice.test(remainingLetters);
var compareRemovedList = choice.test(removedLetters);
for (m = 0; m < splitWord.length; m++){
//alert(splitWord[m]);
if(playerGuess == splitWord[m]){
document.getElementById(splitWord[m]).innerHTML = playerGuess;
}
}
}
//check playerGuess against selectedWord
function checkPlayerChoice(){
var choice = new RegExp(playerGuess);
var compareWord = choice.test(selectedWord.toLowerCase());
var compareAlphabet = choice.test(remainingLetters);
var compareRemovedList = choice.test(removedLetters);
if(compareWord == true && compareAlphabet == true ){
document.getElementById("demo").innerHTML = playerGuess;
remainingLetters.splice(remainingLetters.indexOf(playerGuess),1);
displayAvailableLetters();
displayRemovedLetters();
score++;
updateScore();
checkScore();
}else if(compareWord == true && compareAlphabet == false){
document.getElementById("demo").innerHTML = "Already tried that one";
}else if(compareWord == false && compareAlphabet == true){
livesRemaining--;
document.getElementById("lives").innerHTML = livesRemaining;
removedLetters.push(playerGuess.toLowerCase());
remainingLetters.splice(remainingLetters.indexOf(playerGuess),1);
updateScore();
checkScore();
displayAvailableLetters();
displayRemovedLetters();
}else if (compareWord == false && compareAlphabet == false && compareRemovedList == true){
document.getElementById("demo").innerHTML = "Already tried that one ;)";
}else if (compareWord == false && compareAlphabet == false && compareRemovedList == true){
}else{
/*livesRemaining--;
document.getElementById("lives").innerHTML = livesRemaining;
removedLetters.push(playerGuess.toLowerCase());
updateScore();
checkScore();
displayAvailableLetters();
displayRemovedLetters();*/
document.getElementById("demo").innerHTML = "Not a Valid Key";
}
}
//document.onkeyup = function myKeyDown(event){
// playerGuess = event.key;
//}
//start / Restart the game
function resetGame() {
livesRemaining = 12;
score =0;
wordWorth = 0;
clearTiles();
document.getElementById("lives").innerHTML = livesRemaining;
chooseAWord();
printWord();
buildTiles();
refreshAlphabet();
gameOn=true;
}
.tileStyle{
width:30px;
height:30px;
border:1px solid black;
background-color:green;
float:left;
margin-left:10px;
margin-right:10px;
margin-bottom:10px;
margin-top:10px;
}
.blankStyle{
width:30px;
height:30px;
background-color:orange;
float:left;
margin-left:10px;
margin-right:10px;
margin-bottom:10px;
margin-top:10px;
}
.fixer{
width:100%;
height:10px;
clear:both;
}
<body>
<button onclick="checkPlayerChoice()">Try it</button>
<p id="demo"></p>
<p> lives: </p>
<p id = "lives"> 0</p>
<p> Score: </p>
<p id = "scoreTotal">0</p>
<p>wins</p>
<p id ="winTotals">0</p>
<p>losses</p>
<p id ="lossTotals">0</p>
<p id ="gameOver"></p>
<button onclick ="resetGame()">New Game</button>
<p>Here is the word</p>
<p id = "wordDisplayer">Press New Game to Start</p>
<div id = "wordTiles"></div>
<div class ="fixer"></div>
<button onclick ="checkPlayerGuess()">What Key was Pressed?</button>
<p id ="isThisWorking">What will I say?</p>
<p>Letters Still Available</p>
<p id ="lettersStillAvailable"></p>
<p>Bad Guesses</p>
<p id ="lettersUsed"></p>
<br />
selectedWord ="food";
function checkPlayerChoiceNew(){
var splitWord = selectedWord.split("");
var choice = new RegExp(playerGuess);
var compareWord = choice.test(selectedWord.toLowerCase());
var compareAlphabet = choice.test(remainingLetters);
var compareRemovedList = choice.test(removedLetters);
for (m = 0; m < splitWord.length; m++){
//alert(splitWord[m]);
if(playerGuess == splitWord[m]){
document.getElementById(splitWord[m]).innerHTML = choice;
}
}
}
You can refer this below logic. In this example, I have given some inputs.
var selectedWord ="food";
var displayString = [];
for(var i = 0; i < selectedWord.length; i++){
displayString[i] = "-"
}
var outputEle = document.getElementById("output");
var div = document.createElement('div');
div.innerText = displayString.join(" ");
outputEle.appendChild(div);
function checkPlayerChoiceNew(playerGuess){
var newWord = "";
var regExp = new RegExp(playerGuess,'ig')
selectedWord.replace(regExp, function(value, index){
displayString[index] = value;
return value;
});
var div = document.createElement('div');
div.innerText = displayString.join(" ");
outputEle.appendChild(div);
newWord = displayString.join("");
if(selectedWord == newWord){ alert("You Won the game"); }
//outputEle.innerText = displayString.join(" ");
}
checkPlayerChoiceNew('o');
checkPlayerChoiceNew('g');
checkPlayerChoiceNew('d');
checkPlayerChoiceNew('f');
<div id="output">
</div>

Percentage bar goes up as button is pressed

the code so far
Now if you press a button, no matter which one, a div and a percentage will be shown. I've got that going for me, but if one div is toggled, and another one is pressed, the 66% div should be toggled and so on if two divs are shown and the third is toggled the 100% div should show up.
Basicly if you click a button, a div and a percentage div is revealed if you click aonther the percentage bar goes up. How do I do this? if two divs are toggled and if you press the button two diffrent divs are shown?
JS
function showhide()
{
var div = document.getElementById("lol");
var id3 = document.getElementById("3");
var id5 = document.getElementById("5");
if (div.style.display !== "none")
{
div.style.display = "none";
id3.style.display = "none";
}
else {
div.style.display = "block";
}
}
function showhide2()
{
var div2 = document.getElementById("lol2");
if (div2.style.display !== "none") {
div2.style.display = "none";
}
else {
div2.style.display = "block";
}
}
function showhide3()
{
var div3 = document.getElementById("lol3");
if (div3.style.display !== "none") {
div3.style.display = "none";
}
else {
div3.style.display = "block";
}
}
HTML
<!DOCTYPE html>
<html>
<head>
<title>HTML5, CSS3 and JavaScript demo</title>
</head>
<body>
<!-- Start your code here -->
<div id="lol"><p>div1</p></div>
<div id="lol2"><p>div2</p></div>
<div id="lol3"><p>div3</p></div>
<button id="button" onclick="showhide()">div1</button>
<button id="button" onclick="showhide2()">div2</button>
<button id="button" onclick="showhide3()">div3</button>
<div id = "3"><p>33%</p></div>
<div id = "5"><p>66%</p></div>
<div id = "5"><p>100%</p></div>
<!-- End your code here -->
</body>
</html>
Not entirely sure what you mean but I think it might be something like this?
http://liveweave.com/PcZ7vL
HTML:
<!DOCTYPE html>
<html>
<head>
<title>HTML5, CSS3 and JavaScript demo</title>
</head>
<body>
<div id="lol1"><p>div1</p></div>
<div id="lol2"><p>div2</p></div>
<div id="lol3"><p>div3</p></div>
<button id="button" onclick="showhide()">div1</button>
<button id="button" onclick="showhide2()">div2</button>
<button id="button" onclick="showhide3()">div3</button>
<div id = "3"><p>33%</p></div>
<div id = "5"><p>66%</p></div>
<div id = "7"><p>100%</p></div>
</body>
</html>
JavaScript:
var one = 0
var two = 0
var three = 0
var id3 = document.getElementById("3");
var id5 = document.getElementById("5");
var id7 = document.getElementById("7");
var div1 = document.getElementById("lol1");
var div2 = document.getElementById("lol2");
var div3 = document.getElementById("lol3");
id3.style.display = "none";
id5.style.display = "none";
id7.style.display = "none";
div1.style.display = "none";
div2.style.display = "none";
div3.style.display = "none";
function showhide()
{
if (div1.style.display !== "none")
{
div1.style.display = "none";
one = 0
}
else {
div1.style.display = "block";
one = 1
}
showper();
}
function showhide2()
{
if (div2.style.display !== "none") {
div2.style.display = "none";
two = 0
}
else {
div2.style.display = "block";
two = 1
}
showper()
}
function showhide3()
{
if (div3.style.display !== "none") {
div3.style.display = "none";
three = 0
}
else {
div3.style.display = "block";
three = 1
}
showper()
}
function showper()
{
var sum = one + two + three
id3.style.display = "none";
id5.style.display = "none";
id7.style.display = "none";
if (sum == 1) {
id3.style.display = "block";
} else if (sum == 2) {
id5.style.display = "block";
} else if (sum == 3) {
id7.style.display = "block";
}
else {
id3.style.display = "none";
id5.style.display = "none";
id7.style.display = "none";
}
}
EDIT:
A slightly neater way to do it would be this: http://liveweave.com/YAHn55.
Also, you should take a look at jQuery, makes things like this much simpler.
EDIT:
see example

Categories

Resources