why is the if statement not working in js - javascript

window.addEventListener("keyup", addkey);
function addkey(){
var x = event.which || event.keyCode;
var wkey = 0;
var op = 0;
if(x == 87){
wkey += 1;
}
if(wkey == 1 && op == 0){
alert("your doing good!");
op = op + 1;
}
}
What im trying to get to happen here is getting the alert statement to run once and only once but i cant get it to work either way. I tried using a true or false numberical system (the op variable) but that dident work either. What i see happening is when the code runs and the keyup event fires the wkey variable updates once and stays 1 even know it should be going up a numeral each time the w key is pressed. Anyway i am making this code to go along with a tutorial for the game im making. Any and all suggestions i am open to.

This happens because you re-initialize op to 0 every time the function gets called. You can simply delcare op outside of addkey and it will work:
window.addEventListener("keyup", addkey);
var op = 0;
var wkey = 0;
function addkey(event){
var x = event.which || event.keyCode;
if(x == 87){
wkey += 1;
}
if(wkey == 1 && op == 0){
alert("your doing good!");
op += 1;
}
}
You'll also need to pull the declaration of wkey out of the function if you want to successfully count how many times it was pressed.

That's because you define wkey and op on each function run, you should define them out of the function, to make it work as expected.

Each time the function is called,
wkey gets set to 0,
and then 1 is added,
so it will always end up being equal to 1
Try defining wkey as 0 outside of the function.
Or having
if(wkey == null) var wkey = 0;
instead.
If you use this method op is unnecessary. (Unless of course you're using it's value elsewhere.)

Related

Variable Set to undefined

I am fairly new to Javascript and i ran into a problem when creating a chess game . I have already made the board, but when i tried incorporating JS code that would move these peices when i clicked on them, a problem arose. See i declared the variable "x" to hold the value of the chess peice value that had been clicked on when count=0 but when i tried it out, the code just outputs x as 'undefined'.What have i done wrong, any help would be appreciated :)
(below is a snippet of my JS code)
<div onclick="changeText(63)"id="63"class="black">♘</div>
<div onclick="changeText(64)"id="64"class="white">♖</div>
</div>
<script>
var count = 0;
var x;
function changeText(id) {
if (count > 1){
count = 0;
}
if(count=0){
x = document.getElementById(id).innerHTML;
document.getElementbyId(id).innerHTML="";
}
if(count=1){
document.getElementById(id).innerHTML=x;
}
count = count + 1;
}
</script>
The second and third if statements will not be evaluating the variable value - because rather than comparison (count=== 0) what happens there is a variable assignment (count = 0).
The if (count = 0) is evaluated to false, so, the variable x never gets a value.
On the other hand if (count = 1) is evaluated to true. So, the HTML element gets an undefined string. Your code should look like this:
...
if (count === 0){
x = document.getElementById(id).innerHTML;
document.getElementbyId(id).innerHTML="";
}
if( count === 1){
document.getElementById(id).innerHTML=x;
}
Reference: https://www.w3schools.com/js/js_comparisons.asp
You don't need to pass the id to that handler function if it's doing the same thing. If you want a function that changes the innerHTML of the thing that was clicked, try passing event to the handler, and then using event.target.innerHTML like this:
<div onclick="changeText(event)" class="black">♘</div>
<div onclick="changeText(event)" class="white">♖</div>
<script>
function changeText(event) {
if (event.target.innerHTML === 'x') {
event.target.innerHTML = 'y' // you can do anything here
} else {
event.target.innerHTML = 'x'
}
}
</script>

Why won't one part of my javascript function run even though it is syntactically correct?

I'm a programming newbie trying to make a function that asks for a password, but will display an error message if the password attempt is wrong more than five times. I have tried fiddling around with those code a bunch of different ways and it just won't work. I have a variable called count that starts as 0, and each time a wrong password is entered, 1 is supposed to be added to count, and once count is greater than 5, the error message is supposed to be displayed.
document.getElementById("word-checker").onclick = function () {
var count = 0;
var inputValue = document.getElementById("text-input").value;
var secretWord = "password123";
if (count > 5) {
alert("You have had 5 unsuccessful login attempts. You account has been temporarily locked.");
} else if (inputValue == secretWord) {
alert("Your answer is correct!");
document.getElementById("text-input").value = "";
} else if (inputValue!==secretWord) {
count++;
alert("Your answer is incorrect. Please try again.");
document.getElementById("text-input").value = "";
}
}
This is driving me insane. I'm sure it's a simple beginner's mistake though. Any input that would help me understand why this won't work would be met with a lot of gratitude.
You are resetting count to 0 every time the click event is triggered:
document.getElementById("word-checker").onclick = function () {
var count = 0; // <-- button clicked, set the value to zero.
// ...
}
This means that count will never get to 5 (in fact, it never gets to be > 1 either, as when count++ increments the value to 1, it is set back to 0 on the next click). Consequently, the if (count > 5) part of the if statement will never be triggered.
You need to declare count outside of the click event:
var count = 0;
document.getElementById("word-checker").onclick = function () {
// use count here
// ...
}
you are redefining count as 0 every time on the click event. You need to define count as a global outside the function and then ++ on every error.
Also, try to correct your indentation as it helps reading.

function on every keypress

I want to run the following block on every keypress of right arrow (39):
$(document).ready(function() {
$(document).keydown(function(e) {
var pos = 10;
if (e.keycode = 39) {
if (pos > 10) {
pos + 10;
}
$(".mario").css('left', pos);
}
});
});
The goal is I am setting a variable, pos, and referencing it in a css() method to move it across the screen in increments of 10, every time the key is pressed the expected behavior is on every right arrow key hit, the object moves across the screen in increments of 10.
It works successfully once, then will not continue to increment. My console is empty/free of errors. I have also tried using keypress:
$(document).ready(function() {
$(document).keypress(function(e) {
var pos = 10;
if (e.keycode = 39) {
if (pos > 10) {
pos + 10;
}
$(".mario").css('left', pos);
}
});
});
To elaborate on this, I also want to add an option to check if the left key is pressed and if so, set it back flush against the screen. I went about this by adding the below block under the closing of the first if statement:
else if (e.keycode = 37) {
$(".mario").css('left', '0');
}
I researched on MDN and it simply states: "The keydown event is fired when a key is pressed down." https://developer.mozilla.org/en-US/docs/Web/Events/keydown
Reading that, what I'm not understanding is why is my event only firing once? How come adding a second condition for the left arrow key doesn't register as an event, if the event is fired every time a key is pressed?
See fiddle here: https://jsfiddle.net/c2fr7rsd/1/
EDIT/UPDATE: As many pointed out, I was/am using an assignment operator = and not a comparison === - I initially tried comparison it doesn't work. Assignment - it works, but now all the keycodes register as 39! Howcome in this instance, the comparison operator doesn't reference the keycode?
UPDATE #2 - using e.which is the correct way to handle keydown events, and using the correct comparison === works
The pos variable should be declared as a global.(outside the function).
Right now, each time that function is called, the variable is set back to 10.
Also logic for checking that variable should be
if(pos >= 10)
And setting the variable should be
pos += 10
Also capitalize C in keyCode and the == will work
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
This shows why your logic for if(e.keycode = 39) was returning true
https://www.w3schools.com/js/js_mistakes.asp
Correct code example
$(document).ready(function() {
var pos = 10;
$(document).keypress(function(e) {
if (e.keyCode == 39) {
if (pos >= 10) {
pos += 10;
}
$(".mario").css('left', pos);
}
});
});

Store score in a variable after an event

Desirable result: After the user choose an answer, I want to modify score variable in:
score += 1 if the answer is right either not changing at all if the answer is wrong.
Current result: For every choice user is making, the score remains the same: 0.
First, I store the paragraph that will be changed in question_paragraph and the button that will be clicked by user in next_button. Also, I stored the value(I put the attribute value on every input using the array notation - 0 first, 1 second etc.) in user_answer.
var question_paragraph = document.getElementById('question');
var next_button = document.getElementById('next');
var i = 0;
var user_answer = getCheckedValue(document.getElementsByName('choice'));
var y = 0;
var score = 0;
The getCheckedValue function will return the value attribute of my input if exists.
function getCheckedValue(radioObj) {
var radioLength = radioObj.length;
for(var z = 0; z < radioLength; z++) {
if(radioObj[z].checked) {
return radioObj[z].value;
}
}
return "Error!";
}
Here is the problem. The function works fine, except the isolated area. allQuestion is my object where I stored the questions, the possible answers and the right answer, correctAnswer(I don't included it here but works correctly). I put a conditional statement to increase y and code>score with one if the allQuestions[y].correctAnswer is qual with the value of the user_choice.
function changeQuestion() {
//PROBLEM
if(allQuestions[y].correctAnswer == user_answer){
score += 1;
y++;
} else{y++;}
//PROBLEM
i = (i < allQuestions.length) ? (i + 1) : 0;
if (i == allQuestions.length) {
i = 0;
return question_paragraph.replaceChild(document.createTextNode(allQuestions[0].question), question_paragraph.firstChild);
}
var newNode = document.createTextNode(allQuestions[i].question);
console.log(score);
return question_paragraph.replaceChild(newNode, question_paragraph.firstChild);
}
Finnaly, I called the addHandler function.
function addHandler(name, type, handler){
if (name.addEventListener){
name.addEventListener(type, handler, false);
} else if (name.attachEvent){
name.attachEvent("on" + type, handler);
} else {
name["on" + type] = handler;
}
}
addHandler(next_button, 'click', changeQuestion);
Well, something just appears to be funny here so far. First of all, I don't see any initialization to the variable y. If y is a global variable that is retaining its value, then maybe there is an issue with your object: allQuestions{}. Could you provide the code for building your object allQuestions{}? Without it, I don't think that I could fully answer this question, but I believe that is where your problem lies.
Oops, this was supposed to be a comment, not an answer, sorry...

Problems using setInterval and clearInterval more than once

I'm getting confused with what's happening here. The quiz works fine the first time. After the first play, though, I get all sorts of problems. I want to click the same button,"#start2", to start and also restart the quiz, ie clear the timer, put all variables back to 0 etc, and display the first question. As if the page had been refreshed, basically.
Instead, I'm getting faster ticking, the timer is incrementing on correct guess and so on. Horrible.
I've used modulo to measure how many times the "#start2" div is clicked. On first click, start timer. On second click - I want to reset the timer. Third click - start timer, and so on.
Any help is massively appreciated.
var n = 0;
var x = 0;
var p = 0;
var incTime;
function a(n) {
var x,y,z;
x = Math.floor((Math.random() * 3))
if(x == 0){y = 1; z = 2}else if(x == 1){y = 0; z = 2}else{y = 0; z = 1}
$("#question_holder2").text(questions[n].q);
$(".answer_holder2").eq(x).text(questions[n].a).data('answer', 'a');
$(".answer_holder2").eq(y).text(questions[n].b).data('answer', 'b');
$(".answer_holder2").eq(z).text(questions[n].c).data('answer', 'c');
}
$(document).ready(function() {
//timing element
function startTimer(x){
$("#start2").text(x);
}
$("#start2").click(function(){
var setTimer;
p++;
//if it's been clicked before
if(p%2 === 0){
clearInterval(setTimer);
$("#start2").text("Start");
n = 0;
x = 0;
a(n);
alert("okay");
}else if(p%2 !== 0){
//never been clicked before
a(n);
setTimer = setInterval(function(){startTimer(x=x+1)}, 1000);
$('.answer_holder2').click(function() {
//correct answer given
if ($(this).data('answer') === 'a') {
n++;
if (n < questions.length) {
a(n);
} else {
alert("End of quiz!");
clearInterval(setTimer);
$("#start2").text("You took " + x + " seconds, you answered " + n + " questions correctly, with - incorrect answers given.");
x = 0;
n = 0;
a(n);
}
}else{
//incorrect answer given
$(this).fadeTo(1000,0.4);
var timeString = $("#start2").text();
var incTime = (timeString * 1) + 5;
$("#start2").text(incTime);
startTimer(incTime);
x = incTime;
};
});
};
});
});
You have this:
$("#start2").click(function(){
var setTimer;
p++;
//if it's been clicked before
if(p%2 === 0){
clearInterval(setTimer);
//....
In this case, when you set to the clearInterval line, setTimer will always be 0, and not the id of a running timer. So this is not actually stopping any timer. If you don't stop the timer it will continue to run. So the function here:
setTimer = setInterval(function(){startTimer(x=x+1)}, 1000);
Will continue to run. So the next time you create a timer, you now have two timers updating x and it'll look like it's running faster.
Try this:
$(document).ready(function() {
var setTimer;
$("#start2").click(function(){
// the rest of your click handler code...
});
//timing element
function startTimer(x){
$("#start2").text(x);
}
}
Your setTimer variable needs to exist in a scope outside of your click handler. As you had it you were declaring a new variable every time so when you try and clear the timer, you are not actually clearing the timer.
Also: freakish's point about how you are reattaching the click handler is also a problem. You need to fix that too.
The answer is that bad things happen because of this:
$("#start2").click(function(){
// some code...
$('.answer_holder2').click(function() {
// some code...
});
});
When you click on #start2 new handler is attached to .answer_holder2. So after for example 3 clicks, .answer_holder2 has 3 handlers attached to it and when you click on it all 3 fire.
You're code is a bit complicated and I'm not going to give you a solution how to fix that. But I can give you a hint. Put inner .click outside of outer .click. You will have to change some code probably, but that has to be done.
EDIT What you could try ( as a fast fix, but not necessarly good ) is adding this:
$('.answer_holder2').off( "click" ).click(function() {
Additonally have a look at Matt's answer.

Categories