If Statement not registering in JavaScript - javascript

I can't figure out why these if statements aren't working. I have tried setting the second one to else if as well and it's still not working.
Basically I want to the code to add 1 to the count variable whenever a button is pressed. The problem is that even though the count++ is working, the if statements aren't registering and I can just keep playing around in the if (count== 0) section.
var player = "X";
var comp = "O";
var count = 0;
console.log(count);
//Code for turn 1
if (count == 0) {
//Code for Div 1
$("#1").one("click", function(){
console.log("hit")
count++;
console.log(count)
if ( $('#1').children().length == 0 ){
$("#1").append("<p>" + player + "</p>");
$("#5").append("<p>" + comp + "</p>");
}
else {
console.log("full");
}
});
//Code for Div 2
$("#2").one("click", function(){
console.log("hit")
count++;
console.log(count);
if ( $('#2').children().length == 0 ){
$("#2").append("<p>" + player + "</p>");
$("#5").append("<p>" + comp + "</p>");
}
else {
console.log("full");
}
});
if (count == 1){
$("#2").one("click", function(){
count++;
if ( $('#2').children().length == 0 ){
$("#2").append("<p>" + player + "</p>");
$("#3").append("<p>" + comp + "</p>");
}
else {
console.log("full");
}
})
console.log(count);};

Any logic that needs to be executed on each click must be triggered by that click. Right now, the ifs at the top level are only run once, not in response to clicks.

You're using $("#1").one, which by definition only works once:
Description: Attach a handler to an event for the elements. The
handler is executed at most once per element per event type. (source)
Change all .one's to .on.

Related

Why doesn't my if statement respond to the changes I made to the variables?

var count = 0;
if(count % 2 == 0) {
for (let i = 0; i < squareStorage.length; i++) {
squareStorage[i].addEventListener("click", function() {
console.log("This is: " + i)
console.log(count%2)
count++;
console.log(count);
});
}
}
else if(count % 2 == 1) {
console.log(count%2)
for (let i = 0; i < squareStorage.length; i++) {
squareStorage[i].addEventListener("click", function() {
console.log("This is (no.2): " + i)
count++;
console.log(count);
}, false);
}
}
Those are part of my code. I wanted the variable count to change as I click on a bunch of divs which I threw into the squareStorage variable. I tried by increasing variable count whenever I click. However, my if statement somehow keeps on running, even when count % 2 is not 0.
Its a common mistake, you need to add your events seperately and then in the event call the code.
Here is example.
let count = 0;
// This method will deal with the logic on each click.
// NOTE: we are not re-doing our events.
const processClick = () => {
if(count%2 == 0) {
console.log(`This is one: count ${count}`);
} else {
console.log(`This is two: count ${count}`);
}
count++;
};
// When document loads we will find all divs and add a click event.
document.addEventListener('DOMContentLoaded', () => {
// Find all our DIV elements and add a click event to them.
document.querySelectorAll('div')
.forEach(div => div.addEventListener('click', processClick));
});
<div>Click</div>
<div>Click</div>
<div>Click</div>
<div>Click</div>
<div>Click</div>
I think you've forgotten to remove the old event listeners which you can do with removeEventListener.
eg:
function myClickFunction {
// ... do stuff for first click function
}
// when loading the 2nd click function you run this
squareStorage[i].removeEventListener('click', myClickFunction)

Button Click Event not working

I just write some JS code for click listener, if a button is clicked more than 5 times in 3 seconds then alert will say you wan otherwise you lost.
But I am getting every time YOU LOST!!
<head>
</head>
<body>
<button>Click!!</button>
<script>
let counter =0;
document.querySelector('button').addEventListener('Click', () => {
counter++;
});
setTimeout(() => {
if(counter > 5) {
alert('You Won!!' + counter);
} else {
alert('You Lost!!' + counter);
}
},3000)
</script>
</body>
you may use lowercase 'click' not 'Click', you didn't call your click event anytime in your sample code.
https://developer.mozilla.org/en-US/docs/Web/Events/click
Minor change on your source code. Now working fine.
let counter =0;
document.querySelector('button').addEventListener('click', () =>counter++);
setTimeout(() => {
if(counter > 5) {
alert('You Won!!' + counter);
} else {
alert('You Lost!!' + counter);
}
},3000)
.col {
float: left;
width: 20%;
}
.row {
width: 100%;
clear:both;
display:block;
}
<button>Click!!</button>
I updated your code, two things I noticed were you used an uppercase for your click event:
addEventListener('Click'
and I also changed the if to alert 'you won' if counter was greater than or equal to 5
if(counter >= 5)
Here's a working fiddle
http://jsfiddle.net/fkvvc1f0/1/
This works fine, Working Demo
I changed "Click" to "click", small case only.
addEventListener('click', () => {})
Might want to check out : JavaScript event listeners are case sensitive.
<button>Click!!</button>
<script>
let counter =0;
document.querySelector('button').addEventListener('click', () => {
counter++;
});
setTimeout(() => {
if(counter > 5) {
alert('You Won!!' + counter);
} else {
alert('You Lost!!' + counter);
}
},3000)
</script>
Result :
LOST :
WON :
You should use external JavaScript and CSS, for caching reasons, but I think you want to see this:
function lameGame(clickElement){
let c = 0;
setTimeout(() => {
if(c > 5) {
alert('You Won!!' + c); // never use alert in real world
}
else{
alert('You Lost!!' + c); // never use alert in real world
}
lameGame(clickElement);
}, 3000);
clickElement.onclick = function(){
c++;
}
}
lameGame(document.querySelector('button'));

How save value of a variable in javascript after executing a method?

I have this code :
var n = 0; // << I want save value of this var
$('.next').click(function () { // << after this method run
n++
});
function run() {
setInterval(function () {
n++;
var slideId = '#' + "slide" + (n);
var dotId = '#' + "dot" + (n);
if (n == settings.slideNumber) {
n = 0;
}
var lastSlideId = '#' + "slide" + (n + 1);
var lastDotId = '#' + "dot" + (n + 1);
$(slideId).css({display: 'none'});
$(dotId).css({backgroundColor: '#1a1a1a'});
$(lastSlideId).css({display: 'block'});
$(lastDotId).css({backgroundColor: '#0AC986'});
}, 2000);
}
run();
After the click event occurred , run method will start from fist and value of n will be zero again .
How i can save the value of n var after click event ?
( Consider that I wrote this method inside a jquery plugin )
You can declare n as the global variable, to keep up to date with the latest value of n.
Also, the click event should be outside of the run function, otherwise, each time you execute run function it will attach a new event listener for the button click.
I have created a sample as per your question. Hope it helps.
let n = 0;
$('#btn').click(function() {
n++;
console.log("Value of n::",n)
});
function run() {
console.log("Value of n::",n)
}
run();
$('#run').click(run);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">Click</button>
<button id="run">Run</button>

skip timer in JavaScript interval

I currently have a function that executes some code within a setInterval method. This is working as expected. The problem is I conditionally execute code within this timer. If the condition is not met it will still wait the timeout until trying again. Is there a way of 'skipping' the delay and only executing it when the condition is met.
You will notice in my demo there is a prolonged delay between outputting paragraph results 4 and 8 (as its delaying in between the checks). I would like there to be a consistent delay throughout the whole procedure.
DEMO https://jsfiddle.net/jdec4h0x/
var intAdd = setInterval(function() {
refIndex++
if(refIndex >= predefinedMaxLimit) {
refIndex = 0;
loopedThrough = true;
}
// if this exists then increment refIndex and try again
if (loopedThrough || !$(".myclass[data-mydata1='" + predefinedData2 + "'][data-mydata2='" + refIndex + "']").length) {
counter++;
$('p').last().after('<p>IN Cond Ref = ' + refIndex + '</p>');
// ** js code within this tiemout **
if (counter >= predefinedOutputP) clearInterval(intAdd);
}
}, 500);
You can't change the delay of the interval. Either you destroy and create an interval as Kevin B said or you use setTimeout, which you have to call every time anyway, and then use a delay or another depending on a condition.
/* ... */
if (conditionIsMet) intAdd = setTimeout(function() {}, 1000);
else intAdd = setTimeout(function() {}, 1);
/* ... */
An example here
There are multjple approaches as pointed out by other users.
I would use setTimeout. I'd put this in a function that resides within a loop. You can do this with a while loop. This then gives the the ability to break out when the condition is met. you will need to increment the timer on each loop.
Fiddle https://jsfiddle.net/jdec4h0x/4/
while (progress) {
refIndex++
if (refIndex >= predefinedMaxLimit) {
refIndex = 0;
loopedThrough = true;
}
if (loopedThrough || !$(".myclass[data-mydata1='" + predefinedData2 + "'][data-mydata2='" + refIndex + "']").length) {
counter++;
myTimer = myTimer + 500;
console.log(refIndex);
myFunction(refIndex);
if (counter >= predefinedOutputP) {
$('p').last().after('<p>Cleared Interval</p>');
progress = false;
}
}
}
function myFunction(ref) {
setTimeout(function() {
$('p').last().after('<p>IN Cond Ref = ' + ref + '</p>');
// ** js code within this tiemout **
}, myTimer)
}

Looping JS Function Until if or else Condition is Met

I have created a function that when called with certain parameters will play out and then either tell the player they won or died based on the math. I have tested the function and it properly works, I set the parameters in the function calling so that the player would win and it displayed the win message alert. But if I increase the monster health to where the player will not win the first time the function is called, the function will not repeat itself as I tried to set up with the "else fight()" (as seen below).
My question is this, how to loop the function with the same parameters as before until the else or else if arguments are met?
Calling the function in HTML:
<a class="button" onclick="javascript:fight(8, 5, 1, 10, 3);">Test fight</a><br>
JS Function:
var playerHealth = 100;
function fight(monsterHealth, monsterDmg, monsterArmor, itemDmg, armorSts) {
newPlayerHealth = playerHealth - monsterDmg / armorSts + 2;
newMonsterHealth = monsterHealth - itemDmg / monsterArmor + 2;
if (playerHealth <= 0) {
alert('You died...');
}
else if (newMonsterHealth <= 0) {
alert('You won!');
}
else
{
var newPlayerHealth = playerHealth;
fight(newMonsterHealth, monsterDmg, monsterArmor, itemDmg, armorSts);
}
}
EDIT: Updated function and it says you win no matter how high the monster's damage or health is.
In your code playerHealth was intialize inside function which was resetting players health to 100 in recursive call.
newMonsterHealth was also not persisted considering recursive calls.
<html>
<head>
<script>
var playerHealth = 100;
function fight(monsterHealth, monsterDmg, monsterArmor, itemDmg, armorSts) {
playerHealth = playerHealth - Math.floor(monsterDmg / armorSts) ;
console.log("player helath"+playerHealth);
monsterHealth = monsterHealth - Math.floor(itemDmg / monsterArmor) ;
console.log("monster helath"+monsterHealth);
if (playerHealth <= 0) {
alert('You died...');
}
else if (monsterHealth <= 0) {
alert('You won!');
}
else fight(monsterHealth, monsterDmg, monsterArmor, itemDmg, armorSts);
}
</script>
</head>
<body>
<a class="button" onclick="javascript:fight(100, 40, 1, 10, 3);">Test fight</a><br>
</body>
</html>
P.S. I removed your +2 logic (I won't understood why you were adding)
You probably need for a recursive function that ends when certain condition will be met.
here is an example:
function recursive(target, i) {
target.innerHTML += '<br>' + i;
console.log('index is', i);
if(i > 100) {
return target.innerHTML += '<br>' + 'END';
}
return recursive(target, ++i);
}
document.addEventListener('DOMContentLoaded', function() {
recursive(document.getElementById('test'), 0)
});
<h1 id="test"></h1>

Categories

Resources