Variable value is not being cleared - javascript

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", ...)

Related

Simon game challenge

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;
}

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>

Store text from dynamically created textareas in localStorage

Problem - I have 2 buttons addNew and submitText. I have created a javascript function for each of these two buttons. The addNewcreates textareas with unique ids (note0, note1...). The submitText is supposed to submit the text from all the dynamically created textareas in localStorage in the (key, value) format (notesList0, data), (notesList1, data) and so on. The code is as follows -
$(document).ready(function(){
var note_id = 0;
$("#addNew").click(function () {
note_id++;
var inputField = $('<p align="center"><br><textarea id="note' + note_id + '" placeholder="Enter note, max limit 200 words" class="form-control" rows="5" style="width:80%;overflow:auto;"></textarea></p>');
$('#textFields').append(inputField);
});
document.getElementById("submitText").addEventListener("click", function(){
var id=0, counter;
var flag=true;
for(counter=0; counter<=note_id; counter++) {
var textData = document.getElementById("note"+counter).value;
alert(textData);
while(flag==true)
{
if(localStorage.getItem("notesList"+id)!=null) {
id++;
}
else {
localStorage.setItem("notesList"+id, textData);
flag=false;
alert("Text saved");
}
}
}
} , false);
});
The addNew works but submitText only saves value of the first textarea. Where am I going wrong?
I guess it's because of flag staying "false" after the first loop:
$(document).ready(function(){
var note_id = 0;
$("#addNew").click(function () {
note_id++;
var inputField = $('<p align="center"><br><textarea id="note' + note_id + '" placeholder="Enter note, max limit 200 words" class="form-control" rows="5" style="width:80%;overflow:auto;"></textarea></p>');
$('#textFields').append(inputField);
});
document.getElementById("submitText").addEventListener("click", function(){
var id=0, counter;
var flag=true;
for(counter=0; counter<=note_id; counter++) {
var textData = document.getElementById("note"+counter).value;
alert(textData);
while(flag==true)
{
if(localStorage.getItem("notesList"+id)!=null) {
id++;
}
else {
localStorage.setItem("notesList"+id, textData);
flag=false;
alert("Text saved");
}
}
flag = true;
}
} , false);
});
Use the following for the submit function to make it work for dynamically created elements:
$(document).on("click", "#submitText", function(){
// Do stuff
})
Make sure the ID is only used once on the page. Otherwise switch to class definition.
$(document).ready(function(){
var note_id = 0;
$("#addNew").click(function () {
note_id++;
var inputField = $('<p align="center"><br><textarea id="note' + note_id + '" placeholder="Enter note, max limit 200 words" class="form-control" rows="5" style="width:80%;overflow:auto;"></textarea></p>');
$('#textFields').append(inputField);
});
document.getElementById("submitText").addEventListener("click", function(){
var id=0, counter;
for(counter=0; counter<=note_id; counter++) {
var flag=true;
var textData = $("#note"+counter).val();
if(textData != undefined && textData != '') {
while(flag==true)
{
if(localStorage.getItem("notesList"+id)!=null) {
id++;
}
else {
localStorage.setItem("notesList"+id, textData);
flag=false;
alert("Text saved");
}
}
}
}
} , false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="addNew">Add new</span>
<span id="submitText">Submit</span>
<div id="textFields"></div>
In case you get error when executing the code, check this link:
Failed to read the 'localStorage' property from 'Window'

how to calculate the time keydown to keyup

this is the code, but it's not work,where is wrong.
<input type="text" name ="name" place="">
<button disabled="disabled">click</button>
<script>
$(function(){
var i = 0;
$('input').keydown(function(event) {
i++;
var temp = i;
setTimeout(function(){
var rate = (i-temp);
console.log(rate);
if(rate--){
$('button').attr('disabled',true);
}else{
$('button').attr('disabled',false);
}
},1000)
});
});
thx so much for you guys help
You can use JavaScript storage which is similar to session variables:
<script>
window.onload = function () {
document.onkeydown=(function (event) {
if (localStorage["Count"] == null) {
localStorage["Count"] = 0;
}
else {
localStorage["Count"]++;
}
alert("The count is: " + localStorage["Count"]);
});
}
</script>
in jquery you can use the following code :
KeyDown :
$("input").keydown(function(){ // when user push the key
// do something !!
});
KeyUp :
$("input").keyup(function(){ // when user is not pushing key enymore
// do something !!
});
Calculate time between keydown and keyup:
timebetween = 0;
var count = null;
$("input").keydown(function(){
timebetween = 0;
count = setInterval(function(){
timebetween++;
}, 1);
});
$("input").keyup(function(){
clearInterval(count);
$("body").append("<br>Time between keydown and keyup is "+timebetween+"ms");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
You can try this it will give you time in miliseconds.
$(document).ready(function(){
var startTime = false, endTime;
$(window).keypress(function(){
if(!startTime){
startTime = $.now();
}
});
$(window).keyup(function(){
endTime = $.now();
var keyPressedTime = (endTime - startTime);
console.info('keyyyUpppp', keyPressedTime)
startTime = false;
});
});
you can use this :
<!DOCTYPE HTML>
<html>
<head>
<title>Js Project</title>
</head>
<body>
<input type="text" id="txt" />
<div id="label"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var time = 0; // pressing time
var pressed = 0; // key is pushed or not ?
var timer = setInterval(calculate, 10); // calculate time
$("#txt").keydown(function(){
pressed = 1;
});
$("#txt").keyup(function(){
pressed = 0;
$("#label").html("Pressing Time : "+time+" ms");
time = 0
});
function calculate() { // increase pressing time if key is pressed !!
if (pressed == 1) {
time += 1;
}
}
</script>
</body>
</html>

slideUp() all the elements but not the selected ones

All I want to do is:
there are 7 numbers and 7 divs, they are linked to each other (nr 0 it's in a relationship with div 0)
when one of the numbers is clicked, it should collapse all the other divs which are not selected
it can be selected more at one time
To sum up, basically, the page has some labels with numbers and 7 divs which are all displayed by default (the divs), but when one or more of them are chosen by clicking on the numbers, the page should display only the chosen divs.
This is what I've been trying to do:
for(var i = 0; i <= 6; i++) {
if(i != (floors[i])) {
$("#lvl" + floors[i]).slideUp();
}
}
More code:
http://jsfiddle.net/LSjg4/
Try
var floors = [];
var $lvls = $('.lvl'), $nrs = $(".nr");
$nrs.click(function () {
var $nr = $(this), index = $nrs.index($nr), $lvl = $lvls.eq(index);
$lvl.add($nr).toggleClass('active');
if($nr.hasClass('active')){
$lvls.not('.active').slideUp();
$lvl.slideDown();
$nr.css("background-color", "#1b7664");
$nr.css("border-color", "#236959");
floors.push(($nr).text());
} else {
$nr.css("background-color", "#02c099");
$nr.css("border-color", "#13a480");
if($nrs.filter('.active').length == 0){
$lvls.slideDown();
} else {
$lvls.not('.active').slideUp();
}
var text = $nr.text();
floors.splice($.inArray(text, floors), 1);
}
console.log('floors', JSON.stringify(floors))
});
Demo: Fiddle
I corrected a few things in your code. Here is the below working code and link to it in jsfiddle.
There was a data type mismatch(comparing string and int). When matching whether it exists in floors array, the code was checking floors[i] only whereas the i can be any position in floors.
var floors = [];
$(".nr").click(function () {
var state = $(this).data('state');
state = !state;
if (state) {
$(this).css("background-color", "#1b7664");
$(this).css("border-color", "#236959");
floors.push(parseInt($(this).text()));
console.log(floors);
for(var i = 0; i <= 6; i++) {
ret = $.inArray(i, floors);
if(ret==-1) {
$("#lvl" + i).slideUp();
}
else {
$("#lvl" + i).slideDown();
}
}
} else {
$(this).css("background-color", "#02c099");
$(this).css("border-color", "#13a480");
for (var i = 0; i < floors.length; i++) {
if (floors[i] == parseInt($(this).text()))
floors.splice(i, 1);
}
for(var i = 0; i <= 6; i++) {
ret = $.inArray(i, floors);
if(ret==-1) {
$("#lvl" + i).slideUp();
}
else {
$("#lvl" + i).slideDown();
}
}
}
$(this).data('state', state);
});
Demo Here: http://jsfiddle.net/bFe9T/
I believe this is what you're looking for:
$(".nr").click(function () {
$(this).toggleClass('selected');
$('.nr').each(function(){
var $target = $('#lvl'+$(this).text());
if($(this).is('.selected'))
$target.slideDown();
else
$target.slideUp();
});
});
Note that instead of changing the CSS properties I set up a class for the selected elements
Demo fiddle
Try this
$(".nr").click(function () {
//alert($(this).attr("data-select"));
if($(this).attr("data-select") === "1") {
$(this).attr("data-select","0");
} else {
$(this).attr("data-select","1");
}
$(".nr").each(function(){
if($(this).attr("data-select") === "1") {
var id = $(this).text();
$("div#lvl"+id).slideDown();
} else {
var id1 = $(this).text();
$("div#lvl"+id1).slideUp();
}
});
});
FIDDLE
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>slideUp demo</title>
<style>
.norm { background:#cccccc; margin:3px; width:80px;height:40px; float:left;color:#000000 }
.faded { background:#ffffff; margin:3px; width:80px;height:40px; float:left;color:#ffffff }
.btn{width:80px;}
</style>
<script src="http://code.jquery.com/jquery-1.8.1.js"></script>
</head>
<body>
<button class="btn" onClick="show(1)">1</button>
<button class="btn" onClick="show(2)">2</button>
<button class="btn" onClick="show(3)">3</button>
<button class="btn" onClick="show(4)">4</button>
<button class="btn" onClick="reset()">Reset</button>
<div class="norm" id="slide1">1</div>
<div class="norm" id="slide2">2</div>
<div class="norm" id="slide3">3</div>
<div class="norm" id="slide4">4</div>
<div></div>
<script>
var save = new Array();
function show(indx){
if($.inArray(indx, save)==-1){
save.push(indx);
for(var i=0;i<5;i++){
if($.inArray(i, save)==-1){
$('#slide'+i).attr('class','faded');
}
else{
$('#slide'+i).attr('class','norm');
}
}
}
}
function reset(){
save = new Array();
for(var i=0;i<5;i++){
$('#slide'+i).attr('class','norm');
}
}
</script>
</body>
</html>

Categories

Resources