Simon game challenge - javascript

I want to compare the recent user pattern("userPattern") with the randomly generated pattern("gamePattern").and if userPattern eual to gamepattern I want to enter into next level.
Ho to do that? now I have done up to responding to the user's click.
My HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
href="https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap"
rel="stylesheet"
/>
<link rel="stylesheet" href="style.css" />
<title>Document</title>
</head>
<body>
<h1>Press A Key To Start</h1>
<main>
<button type="button" id="green" class="green box"></button>
<button type="button" id="red" class="red box"></button>
<button type="button" id="yellow" class="yellow box"></button>
<button type="button" id="blue" class="blue box"></button>
</main>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="index.js"></script>
</body>
</html>
My JS code:
var color = ["green", "red", "yellow", "blue"];
var gamePattern = [];
var userPattern = [];
var level = 0;
function newSequence() {
var randomNumber = Math.floor(Math.random() * 4);
var colorChosen = color[randomNumber];
var audio = new Audio("sounds/" + colorChosen + ".mp3");
audio.play();
$("#" + colorChosen)
.fadeOut(250)
.fadeIn(250);
gamePattern.push(colorChosen);
$("h1").text("Level " + level);
level++;
var userColorChosen;
for (var i = 0; i < $("button").length; i++) {
$("#" + color[i]).click(function () {
userColorChosen = this.id;
userPattern.push(userColorChosen);
var audio = new Audio("sounds/" + userColorChosen + ".mp3");
audio.play();
$("#" + userColorChosen)
.fadeOut(100)
.fadeIn(100);
});
}
}
var call = true;
$(document).keypress(function () {
if (call === true) {
newSequence();
}
call = false;
});
Please help me.

My answer using Jquery for Simon Game:
var color = ["green", "red", "yellow", "blue"];
var gamePattern = [];
var userPattern = [];
var level = 0;
$("button").click(function () {
var userColorChosen = $(this).attr("id");
userPattern.push(userColorChosen);
var audio = new Audio("sounds/" + userColorChosen + ".mp3");
audio.play();
$("#" + userColorChosen)
.fadeOut(100)
.fadeIn(100);
checkAnswer(userPattern.length - 1);
});
function checkAnswer(currentLevel) {
if (userPattern[currentLevel] === gamePattern[currentLevel]) {
if (userPattern.length === gamePattern.length) {
setTimeout(function () {
newSequence();
}, 1000);
}
} else {
$("h1").text("GAMEOVER");
var audio = new Audio("sounds/wrong.mp3");
audio.play();
$("body").addClass("gameover");
setTimeout(function () {
$("body").removeClass("gameover");
}, 100);
startOver();
}
}
function newSequence() {
userPattern = [];
level++;
$("h1").text("Level " + level);
var randomNumber = Math.floor(Math.random() * 4);
var colorChosen = color[randomNumber];
gamePattern.push(colorChosen);
var audio = new Audio("sounds/" + colorChosen + ".mp3");
audio.play();
$("#" + colorChosen)
.fadeOut(250)
.fadeIn(250);
}
var call = true;
$(document).keypress(function () {
if (call === true) {
newSequence();
call = false;
}
});
function startOver() {
level = 0;
gamePattern = [];
call = true;
}

Related

Session storage value showing null

I keep on getting null every time I try to store values in Section B and C but works fine for A. I can't seem to find where the issue is. I am trying to have a user's info display on a different page based on the section he chooses. If the user chooses section B for example I would want to let the user know on the next page that he/she has ordered a seat in Section B and whatever the available seat is along with the name and price. After the boarding pass is displayed on the next page, I want the array to change from having 5 seats to 4 and keep this array updated everytime a new person signs up.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src = "airplane.js"></script>
</head>
<style>
</style>
<body>
<h1>Welcome To Air France</h1>
<h2>Choose your seat section here</h2>
<h3>Section A</h3>
<p>Price:</p>
<div id = "Section1Price"></div>
<div id = "Section1"></div>
<form action = "bookingPage.html" method="post">
<p>Enter your full name to book in this section:</p>
<input id="clientNameA" type="text" size="25" height="25">
<input id = "bookSeatA" type="button" onclick="location.href='bookingPage.html';" value="Book a Seat in Section A" />
</form>
<h3>Section B</h3>
<p>Price:</p>
<div id = "Section2Price"></div>
<div id = "Section2"></div>
<form action = "bookingPage.html" method="post">
<p>Enter your full name to book in this section:</p>
<input id="clientNameB" type="text" size="25" height="25">
<input id = "bookSeatB" type = "button" onclick="location.href='bookingPage.html';" value = "Book a Seat in Section B">
</form>
<h3>Section C</h3>
<p>Price:</p>
<div id = "Section3Price"></div>
<div id = "Section3"></div>
<form action = "bookingPage.html" method="post">
<p>Enter your full name to book in this section:</p>
<input id="clientNameC" type="text" size="25" height="25">
<input id = "bookSeatC" type = "button" onclick="location.href='bookingPage.html';" value = "Book a Seat in Section C">
</form>
</body>
</html>
airplane.js
function start()
{
var price1;
price1 = Math.random() * (200 - 100) + 100;
price1 = price1.toFixed(2);
var price2 = (Math.random() * (300 - 100) + 100).toFixed(2);
var price3 = (Math.random() * (300 - 100) + 100).toFixed(2);
var priceArray = [price1, price2, price3];
var sectionASeats = [];
var sectionBSeats = [];
var sectionCSeats = [];
for (var k = 0; k < 5; k++)
{
sectionASeats[k] = 0;
sectionBSeats[k] = 0;
sectionCSeats[k] = 0;
}
var buttonA = document.getElementById( "bookSeatA" );
buttonA.addEventListener( "click", function() {bookSeat(sectionASeats)}, false );
buttonA.addEventListener("click",function(){handleSubmitA(priceArray[0],sectionASeats,"A")}, false );
var buttonB = document.getElementById( "bookSeatB" );
buttonB.addEventListener( "click", function() {bookSeat(sectionBSeats)}, false );
buttonB.addEventListener("click",function(){handleSubmitB(priceArray[1]),sectionBSeats,"B"}, false );
var buttonC = document.getElementById( "bookSeatC" );
buttonC.addEventListener( "click", function() {bookSeat(sectionCSeats)}, false );
buttonC.addEventListener("click",function(){handleSubmitC(priceArray[2]),sectionCSeats,"C"}, false );
var result1 = "";
var result2 = "" ;
var result3 = "" ;
result1 += checkSection(sectionASeats, "A" );
result2 += checkSection(sectionBSeats, "B" );
result3 += checkSection(sectionCSeats, "C" );
priceArray.sort(function(a,b) {return a-b});
document.getElementById("Section1Price").innerHTML = "$" + priceArray[0];
document.getElementById("Section1").innerHTML = result1;
document.getElementById("Section2Price").innerHTML = "$" + priceArray[1];
document.getElementById("Section2").innerHTML = result2;
document.getElementById("Section3Price").innerHTML ="$" + priceArray[2];
document.getElementById("Section3").innerHTML = result3;
}
function sectionSeatNum (array)
{
for (var i = 0; i < array.length;i++)
{
if (array[i] == 1)
{
return i+1;
}
}
}
function handleSubmitA(priceForA,array,section)
{
const name = document.getElementById("clientNameA").value;
var seatNumber = sectionSeatNum(array);
sessionStorage.setItem("ARRAY", JSON.stringify(array));
sessionStorage.setItem("SECTION", section);
sessionStorage.setItem("SEATNUM", seatNumber);
sessionStorage.setItem("NAME", name);
sessionStorage.setItem("PRICE", priceForA);
return;
}
function handleSubmitB(priceForB,array,section)
{
const name = document.getElementById("clientNameB").value;
var seatNumber = sectionSeatNum(array);
sessionStorage.setItem("ARRAY", JSON.stringify(array));
sessionStorage.setItem("SECTION", section);
sessionStorage.setItem("SEATNUM", seatNumber);
sessionStorage.setItem("NAME", name);
sessionStorage.setItem("PRICE", priceForB);
return;
}
function handleSubmitC(priceForC,array,section)
{
const name = document.getElementById("clientNameC").value;
var seatNumber = sectionSeatNum(array);
sessionStorage.setItem("ARRAY", JSON.stringify(array));
sessionStorage.setItem("SECTION", section);
sessionStorage.setItem("SEATNUM", seatNumber);
sessionStorage.setItem("NAME", name);
sessionStorage.setItem("PRICE", priceForC);
return;
}
function bookSeat(array)
{
for(var i = 0; i < array.length; i++)
{
if(array[i] == 0)
{
array[i] = 1;
break;
}
}
}
function checkSection(array, section)
{
var result;
var check = true;
var emptyCounter = 0;
var takenCounter = 0;
for (var i = 0;i<array.length;i++)
{
if(array[i] == 0)
{
emptyCounter++;
}
else{
takenCounter++;
}
}
if(takenCounter == array.length)
{
check = false;
result = "<p>There are no seats available in Section " + section + ".</p>";
}
else{
check = true;
result = "<p>There are " + emptyCounter + " seats available in Section " + section + ".</p>";
}
return result;
}
window.addEventListener("load", start,false);
bookingPage.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src = "booking.js"></script>
</head>
<body>
<h1>Thank you for choosing Air France</h1>
<h2>Here is your boarding pass</h2>
<h3 id="booking-name"></h3>
<form action="index.html" method="get">
<input id = "backToHome" type="button" onclick="location.href='index.html';" value="Return to Homepage">
</form>
</body>
</html>
booking.js
function start()
{
const name = sessionStorage.getItem("NAME");
const price = sessionStorage.getItem("PRICE");
const arrayBookings = JSON.parse(sessionStorage.getItem("ARRAY"));
const section = sessionStorage.getItem("SECTION");
var seatNum = sessionStorage.getItem("SEATNUM")
var result = "";
result += "<p> Thank you " +name+ " for flying with us. Here is your boarding pass.</p>";
result += "<p> Name: " + name + "</p>";
result += "<p> Section: "+ section + "</p>";
result += "Price: $"+price;
result += "<p>Seat number: "+seatNum+ "</p>";
// result += "<p>"+arrayBookings+"</p>";
document.getElementById("booking-name").innerHTML = result;
}
window.addEventListener("load", start, false);
You have typo here
buttonB.addEventListener("click",function(){handleSubmitB(priceArray[1]),sectionBSeats,"B"}, false );
while you want to have
buttonB.addEventListener("click",function(){handleSubmitB(priceArray[1],sectionBSeats,"B")}, false );
Session C is the same error.

Choosing an item from HTML collection

I'm trying to select the elements(lis)that are pushed into my array(todos its a ul)..
when the function (nu) is called it creates a new li and stores it in an HTML Collection...
I want to be able to select those li for styling.
var input = document.querySelector("#input");
var todos = [];
var list = document.getElementById("list");
var lis = document.getElementsByTagName("li")
var btns = document.querySelectorAll("button")
function nu() {
input.addEventListener("change", function () {
todos.push(input.value)
list.innerHTML += "<li>" + input.value + "</li>"
input.value = ""
})
return list;
}
function alo() {
for (i = 0; i < todos.length; i++) {
lis.item(i).addEventListener("click", function () {
alert("alo")
})
}
}
function disp() {
todos.forEach(i => {
list.innerHTML += "<li>" + i + "</li>"
});
return list;
}
disp()
nu()
I tried to do this
function silly() {
for (i = 0; i < lis.length; i++) {
lis[i].addEventListener("click", function () {
alert("working")
})
}
}
still doesn't work :/..
here is my html
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="new.css">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>New To-do!</title>
</head>
<body>
<div class="container">
<h1>MY TO-DO</h1>
<input type="type" placeholder="New TO-DO" id="input">
<ul id="list">
</ul>
</div>
<script src="todo.js" type="text/javascript"></script>
</body>
</html>
And this is the output, I want to style those todos.!
JSFiddle : https://jsfiddle.net/cytjae3z/
The function you created actually works, I think your problem comes from the fact that you weren't able to call it in the right place, that being in the input.addEventListener. Here is a working example :
var input = document.querySelector("#input");
var todos = [];
var list = document.getElementById("list");
var lis = document.getElementsByTagName("li")
var btns = document.querySelectorAll("button")
function nu() {
input.addEventListener("change", function() {
todos.push(input.value)
list.innerHTML += "<li>" + input.value + "</li>"
input.value = ""
silly()
})
return list;
}
function alo() {
for (i = 0; i < todos.length; i++) {
lis.item(i).addEventListener("click", function() {
alert("alo")
})
}
}
function disp() {
todos.forEach(i => {
list.innerHTML += "<li>" + i + "</li>"
});
return list;
}
function silly() {
for (i = 0; i < lis.length; i++) {
lis[i].addEventListener("click", function() {
this.style.backgroundColor = "#" + ((1 << 24) * Math.random() | 0).toString(16)
})
}
}
disp()
nu()
<div class="container">
<h1>MY TO-DO</h1>
<input type="type" placeholder="New TO-DO" id="input">
<ul id="list">
</ul>
</div>

Javascript flow control glitch

UPDATE: SOLVED! line 116 (ERROR3) had to be changed from 'parseInst(rom[i]); ' to 'rom[i]; '.
I'm working on an assembly simulator in Javascript. For some reason the JUMP instruction messes up the register contents. The following program (can be copy-pasted) increments register 'A' (0-->1) then jumps to instruction 0. Instead of '1', the register's content becomes a value over 5000. What am I doing wrong? UPDATE: added three errors caught by the debugger ("Uncaught RangeError: Maximum call stack size exceeded").
var regA = 0;
var regB = 0;
var accu = 0;
var rom = [];
var instCount = 0;
var flag1 = 0;
var stopState = 0;
function eval() {
var inst = document.getElementById("text_f").value;
parseInst(inst);
};
function parseInst(instString) {
if (instString.includes("LDA")) { //ERROR1
var strSplitA = instString.split(":");
regA = parseInt(strSplitA[1]);
document.getElementById("regA").innerHTML = regA;
instCount++;
document.getElementById("demo").innerHTML = "load register A: " + strSplitA[1]+"type of: "+typeof regA;
} else if (instString.includes("LDB")) {
var strSplitB = instString.split(":");
document.getElementById("demo").innerHTML = "load register B: " + strSplitB[1];
regB = parseInt(strSplitB[1]);
document.getElementById("regB").innerHTML = regB;
instCount++;
} else if (instString == "ADD") {
accu = regA + regB;
document.getElementById("demo").innerHTML = "add " + regA + "+" + regB + "=" + accu;
document.getElementById("accu").innerHTML = accu;
instCount++;
} else if (instString.includes("JMP")) {
var jumpTo = instString.split(":");
instCount = parseInt(jumpTo[1]);
document.getElementById("demo").innerHTML = "jump to: " + instCount+" typeof: "+typeof instCount;
document.getElementById("count").innerHTML = instCount;
runStop(stopState,parseInt(jumpTo[1])); //ERROR2
} else if (instString == "CMP") {
if (regA === regB) {
flag1 = 1;
instCount++;
document.getElementById("flag1").innerHTML = 1;
document.getElementById("demo").innerHTML = "flag1 set to 1";
} else {
flag1 = 0;
instCount++;
document.getElementById("flag1").innerHTML = 0;
document.getElementById("demo").innerHTML = "flag1 set to 0";
};
} else if (instString.includes("INC")) {
var incRegister = instString.split(":");
switch (incRegister[1]) {
case "A":
regA++;
document.getElementById("demo").innerHTML = "case A";
document.getElementById("regA").innerHTML = regA;
instCount++;
break;
case "B":
regB++;
document.getElementById("demo").innerHTML = "case B";
document.getElementById("regB").innerHTML = regB;
instCount++;
break;
default:
document.getElementById("demo").innerHTML = "error: register name";
break;
}
} else {
document.getElementById("demo").innerHTML = "error: no instruction";
};
};
function saveToRom() {
var romString = document.getElementById("text_f").value;
rom = romString.split(",");
document.getElementById("rom").innerHTML = rom;
document.getElementById("demo").innerHTML = "#debug:save to rom";
reset();
};
function step() {
parseInst(rom[instCount]);
document.getElementById("count").innerHTML = instCount-1;
};
function run() {
stopState = 0;
document.getElementById("demo").innerHTML = "run";
runStop(stopState,instCount);
};
function stop(){
stopState = 1;
document.getElementById("demo").innerHTML = "stop";
runStop(stopState,instCount);
};
function runStop(stopSt,instructionCount){
if(stopSt == 0){
for(var i=instructionCount;i<rom.length;i++){
parseInst(rom[i]); //ERROR3
document.getElementById("demo").innerHTML = "#runStop(): stopState: "+stopState+" for loop length: " + rom.length;
}
} else {
document.getElementById("demo").innerHTML = "#runStop(): stopState: "+stopState;
};
};
function reset() {
document.getElementById("demo").innerHTML = "debug: reset";
regA = 0;
regB = 0;
accu = 0;
flag1 = 0;
instCount = 0;
document.getElementById("regA").innerHTML = regA;
document.getElementById("regB").innerHTML = regB;
document.getElementById("accu").innerHTML = accu;
document.getElementById("count").innerHTML = instCount;
document.getElementById("flag1").innerHTML = flag1;
};
The full source code with HTML on Github.
I appreciate your help in advance! EDIT: The html code
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>COMPU</title>
<script type='text/javascript' src='comp3.1.js'></script>
<link rel="stylesheet" type="text/css" href="stylesheet_comp.css">
</head>
<body>
<input type="text" id="text_f" value=" " autofocus>
<br><br>
<div class="nav">
<button onclick="eval()">EXEC</button>
<button onclick="saveToRom()">SAVE</button>
<button onclick="reset()">RST</button>
<button onclick="step()">STEP</button>
<button onclick="run()">RUN</button>
<button id="stop" value=0 onclick="stop()">STOP</button>
</div>
<br>
<div class="displays">
DEBUG:
<p id="demo">*debugging messages*</p>
REG A:
<p id="regA">0</p>
REG B:
<p id="regB">0</p>
ACCU:
<p id="accu">0</p>
<br> ROM:
<p id="rom"></p>
INS COUNT:
<p id="count">0</p>
FLAG1:
<p id="flag1">0</p>
<!--
DEBUG2:
<p id="dbg2"></p>
-->
</div>
INSTRUCTIONS:
<ol>
<li>ADD</li>
</ol>
</body>
</html>
UPDATE: SOLVED! line 116 (ERROR3) had to be changed from 'parseInst(rom[i]); ' to 'rom[i]; '.

Creating an HTML 5 audio player

I'm trying to build an html5/javascript mp3 player on my webpage but the site is playing no sound. I have the song in the root directory with my index.html file. Why is it when I hit play on the mp3 file, it doesn't play?
Heres my code:
index.html
<!DOCTYPE html>
<html ng-app>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="css/main.css" media="screen" />
<link href="menu_source/styles.css" rel="stylesheet" type="text/css">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="dist/css/bootstrap.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>
<script src="music.js"></script>
<script>
var player;
var intv;
var slider;
window.onload = function () {
document.getElementById('btnPlay').addEventListener('click', playMusic, false);
document.getElementById('btnPause').addEventListener('click', btnPause, false);
document.getElementById('btnStop').addEventListener('click', btnStop, false);
document.getElementById('btnVolUp').addEventListener('click', , false);
document.getElementById('btnVolDown').addEventListener('click', volDown, false);
player = document.getElementById('player');
slider = document.getElementById('sliderTime');
slider.addEventListener('change', reposition, false);
getMusicList();
}
function reposition() {
player.currentTime = slider.value;
}
//Volume Controls
function volUp() {
if (player.volume < 1) {
player.volume += 0.1;
console.log(player.volume);
} else {
player.volume = 1;
}
}
function volDown() {
if (player.volume > 0) {
player.volume -= 0.1;
console.log(player.volume);
} else {
player.volume = 0;
}
}
//MUSIC PLAY CONTROLS
function playMusic() {
player.play();
intv = setInterval(update, 100);
slider.max = player.duration;
}
function update() {
document.getElementById('songTime').innerHTML = millisToMins(player.currentTime);
slider.value = player.currentTime;
}
function millisToMins(seconds) {
var numminutes = Math.floor((((seconds % 31536000) % 86400) % 3600) / 60);
var numseconds = (((seconds % 31536000) % 86400) % 3600) % 60;
if (numseconds >= 10) {
return "Time Elapsed: " + numminutes + ":" + Math.round(numseconds);
} else {
return "Time Elapsed:" + numminutes + ":0: + Math.round(numseconds);
}
}
function pauseMusic(){
player.pause();
clearInterval(intv);l
}
function stopMusic(){
player.pause();
player.currentTime = 0;
clearInterval(intv);
}
function getMusicList(){
var parser = new DOMParser();
xmlDocument = parser.parseFromString(xml, "
text / xml ");
var elementsArray = xmlDocument.documentElement.getElementsByTagName('composition');
var arrayLength = elementsArray.length;
var output = " < table > ";
for (var i = 0; i < arrayLength, i++){
var title = elementsArray[i].getElementsByTagName('title'[0].firstChild.nodeValue;
var composer = elementsArray[i].getElementsByTagName('composer')[0].firstChild.nodeValue;
var time = elementsArray[i].getElementsByTagName('time')[0].firstChild.nodeValue;
var fileName = elementsArray[i].getElementsByTagName('filename')[0].firstChild.nodeValue;
output += " < tr > ";
output += (" < td onclick = 'songSelect(\"" + fileName + "\")' > " + title + "
By: " + composer + " < /td>");
output += "</table > ";
document.getElementById('musicList').innerHTML = output;
}
function songSelect(fn){
//console.log(fn);
document.getElementById('player').src = fn;
playMusic();
}
</script>
</head>
<body>
<div class="row">
<div class="col-md-4">
<div id="logo2">
<div class="col-md-4">
<div ng-controller="logOut">
<div id="logOut1">
<button type="button" class="btn btn-primary" ng-model="singleModel" btn-checkbox btn-checkbox-true="1" btn-checkbox-false="0">
Logout
</button>
</div>
</div>
</div>
</div>
<script>
angular.module('myModule', ['ui.bootstrap']);
</script>
<script src="angular.min.js"></script>
<div id="content2">
<div id="audioPlayer">
<audio id="player">
<source src="SleepAway.mp3" />
<source src="SleepAway.ogg" />
</audio>
<button id="btnPlay">Play</button>
<button id="btnPause">Pause</button>
<button id="btnStop">Stop</button>
<button id="btnVolUp">Volume Up</button>
<button id="btnVolDown">Volume Down</button>
<span id="songTime"></span>
<br/>
<input id="sliderTime" type="range" min="0" value="0" />
<div id="musicList"></div>
</div>
</body>
</html>
main.js
<script type="text/javascript">
var audio = document.getElementById("player"),
play = document.getElementById("play"),
timer = document.getElementById("timer"),
update;
audio.addEventListener("click, PlayAudio, false);
play.addEventListener("
click, PlayAudio, false);
//play or pause audio
functon PlayAudio(e) {
e.preventDefault();
if (audio.paused) {
audio.play();
play.textContent = "Pause";
} else {
audio.pause();
play.textContent = "Play";
}
}
document.write("Hello World!");
</script>
var player = document.createElement('audio');
player.src = 'your_source_here.mp3';
player.controls = true;
document.body.appendChild(player);

Variable value is not being cleared

This code displays parsed data from php the problem is when I select another set of data which are the parsed the previous data are not being cleared. I have tried emptying the var json but without any positive result.
$(document).ready(function() {
$(".chooseSub").on("click",function(event) {
event.preventDefault();
var display = $(this).attr("title");
var idx = 0;
$.post("includes/learnFunctions.php", {
learnThis:display
}, function(data) {
var json = $.parseJSON(data);
if (json == 0) {
$("#spanQ").html("Nothing to show!");
} else {
workData(json, idx);
}
});
});
function workData(json, idx){
function next() {
if (idx > (json.length - 1)) {
idx = 0;
}
console.log(idx+" next() start");
var text1 = json[idx].question;
var text2 = json[idx].answer;
$("#spanQ").html("<p>" + text1 + "</p>");
$("#spanA").html("<p>" + text2 + "</p>");
console.log(idx,text1,json);
console.log(json );
idx++;
}
$(".test").on("click",function(){
next();
});
}
}); //doc ready
this problem can be simulated here
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>test</title>
<script src="js/jquery-1.10.2.js"></script>
<script>
$(document).ready(function() {
function workData(custVar){
var idx =0;
function again(){
console.warn(custVar);
if (idx > (custVar.length - 1)) {
idx = 0;
}
var text1 = custVar[idx];
$("#spanQ").html("<p>" + text1 + "</p>");
console.log(idx,text1,custVar);
idx++;
}
$("#id4").on("click",function(){
again();
});
}
var customVar1 = ["green", "black", "red", "blue", "yellow"];
var customVar2 = ["one","two", "three", "four", "five"];
$("#id1").on("click", function(){
workData(customVar1);
});
$("#id2").on("click", function(){
workData(customVar2);
});
}); //doc ready
</script>
</head>
<body>
<div id="id1">Colors</div>
<br/>
<div id="id2">Numbers</div>
<br/>
<div id="id4">RUN</div>
<br />
<span id="spanQ"></span>
</div>
</body>
</html>
I have tried couple of different approaches but none of them is working for the interval scenario.
$(document).ready(function() {
var idx = 0;
function workData(custVar){
clearInterval(myInterval);
function again(){
if (idx > (custVar.length - 1)) {
idx = 0;
}
text1 = custVar[idx];
$("#spanQ").html("<p>" + text1 + "</p>");
console.log(idx,text1,custVar);
idx++;
}
var myInterval = setInterval(again, 2000);
}
function manStep(custVar){
if (idx > (custVar.length - 1)) {
idx = 0;
}
text1 = custVar[idx];
$("#spanQ").html("<p>" + text1 + "</p>");
console.log(idx,text1,custVar);
idx++;
};
var customVar1 = ["green", "black", "red", "blue", "yellow"];
var customVar2 = ["one","two", "three", "four", "five"];
$("#id1").on("click", function(){
workData(customVar1);
});
$("#id2").on("click", function(){
workData(customVar2);
});
$("#id3").on("click", function(){
clearInterval(interval);
var interval = setInterval(function(){manStep(customVar1);}, 2000);
});
$("#id4").on("click", function(){
clearInterval(interval);
var interval = setInterval(function(){manStep(customVar2);}, 2000);
});
}); //doc ready
If you add an event handler with $(".test").on("click", ...), this does not cause any previous handlers to be removed. Instead, every run of workData() registers an additional action to carry out on clicking the .test element. This is why you are seeing as many log outputs as calls to workData() were made.
To get rid of this problem, you should remove any existing "click" event handler before adding a new one. jQuery offers the off() function for this purpose:
var test = $(".test");
test.off("click");
test.on("click", ...);
// or: test.off("click").on("click", ...)

Categories

Resources