Why is this function youWin not working properly? - javascript

I believe I'm posting all of the relevant code here.
The function definitely does run because if I switch the > to a < it gives me the alert when I click on the 'moveup' button.
Also, the console logs that pic2 continues to grow with each increment and pic3 stays the same. So that part is working.
Something in the function just isn't comparing the two variables properly and I can't figure out what's wrong.
var player = document.getElementById("pic2").offsetLeft;
var finish = document.getElementById("pic3").offsetLeft;
console.log(player);
console.log(finish);
function youWin() {
if (player >= finish) {
alert("You Win!");
} else {
}
};
$(function() {
$('#moveup').click(function() {
$("#pic2").css('margin-left', '+=2vw');
$("#pic3").css('margin-left', '-=2vw');
document.getElementById("guessField").value = "";
$('#myModalTrue').toggle();
y = regenerate();
var player = document.getElementById("pic2").offsetLeft;
var finish = document.getElementById("pic3").offsetLeft;
console.log(player);
console.log(finish);
youWin();
});
});

you aren't changing the global player and finish variable. you are making new local ones. for more information about variable scope in javascript. try this
var player = document.getElementById("pic2").offsetLeft;
var finish = document.getElementById("pic3").offsetLeft;
console.log(player);
console.log(finish);
function youWin() {
if (player >= finish) {
alert("You Win!");
} else {
}
};
$(function() {
$('#moveup').click(function() {
$("#pic2").css('margin-left', '+=2vw');
$("#pic3").css('margin-left', '-=2vw');
document.getElementById("guessField").value = "";
$('#myModalTrue').toggle();
y = regenerate();
player = document.getElementById("pic2").offsetLeft;//change is here
finish = document.getElementById("pic3").offsetLeft;//and here
console.log(player);
console.log(finish);
youWin();
});
});

Try logging values inside the youWin function it should return old values and your answer. Your player and finish values are not updating for function. It is still getting old values.
function youWin(player, finish) {
if (player >= finish) {
alert("You Win!");
} else {
}
};
$(function() {
$('#moveup').click(function() {
$("#pic2").css('margin-left', '+=2vw');
$("#pic3").css('margin-left', '-=2vw');
document.getElementById("guessField").value = "";
$('#myModalTrue').toggle();
y = regenerate();
var player = document.getElementById("pic2").offsetLeft;
var finish = document.getElementById("pic3").offsetLeft;
console.log(player);
console.log(finish);
youWin(player, finish);
});
});

Related

Changing Attributes of a page based on an if statement

I am working on a Rock, Paper, Scissor page. I made a results page that is loaded after the computer showcase what it choose. What I would like is that base on the results, TWO images change in the result page. I made functions that have the Attributes I want to change but I can't figures out how to make the page run these functions once the result Page is loaded. I am super new to Javascript, so any help would be appreciate it!
const getResult = () => {
computerChoice = rand(0, 3);
finalChoice = imgs[computerChoice];
computer.src = `img/${finalChoice}.png`
computerButton.innerHTML = finalChoice;
console.log(computer.src);
// console.log(imgs.indexOf(finalChoice));
computerIndex = imgs.indexOf(finalChoice)
userChoice = 1;
if (userChoice === computerIndex) {
console.log("is a tied");
setTimeout("resultPage()", 1000);
} else if (userChoice < computerIndex) {
console.log("you win");
setTimeout("resultPage()", 1000);
} else if (userChoice > computerIndex) {
console.log("you lost")
setTimeout("resultPage()", 1000);
}
}
const resultPage = () => {
window.location = "finalResult.html";
}
function loseAttributes() {
let weaponImg = document.querySelector(".finalweapon");
let resultLabel = document.querySelector(".result");
weaponImg.src = "img/weapons-10.png";
resultLabel.src = "img/label2.png";
}
function tieAttributes() {
let weaponImg = document.querySelector(".finalweapon");
weaponImg.src = "img/Scissors.png";
let resultLabel2 = document.querySelector(".result");
resultLabel2.src = "img/label3.png";
}
Well one way to pass a parameter to html page is using the url. So when winning redirect to finalResult.html#win if lose then finalResult.html#lose etc.
Then on load event of the finalResult.html get those parameter using window.location.hash
// finalResult.html
window.addEventListener('load', function() {
var hash = window.location.hash
if (hash === "#win") {
// show win image
}
if (hash === "#lose") {
// show lose image
}
})

World's most persistent bouncing

I used the same algorithm for an earlier part of the code, used a basic de-bouncer on the functions, and it worked, like so:
var lastClick = 0;
var delay = 20;
function l_mage_menu(){
if (lastClick >= (Date.now() - delay))
return;
lastClick = Date.now()
But for this it refuses to work and everything is running 3+ times, whether it's the alert window or the function being called. Cannot for the life of me figure out why.
document.addEventListener("DOMContentLoaded", (function(event) {
var buttons = document.querySelectorAll('.btn');//this acts like an array
if (buttons){
buttons.forEach(function getIndex(curVal2, LIndex2){ //current value and index in the list
curVal2.addEventListener('click', function() {
curVal2.classList.toggle("active2");
buttons.forEach(function(x, sL2){
if(LIndex2 !== sL2) { //if list index is NOT equal to the selected list element, aka one has already been picked
x.classList.remove('active2');
};
current_index2 = LIndex2;
switch(current_index2){
case(0): //basic attack.
console.log("test1") //from here, call the menus
break;
case(1): //this one is spells
//use listener to execute the matching spell
let btn1 = document.getElementById("btn_1");
btn1.addEventListener("click", function(){
if(btn1.innerHTML == "Supreme Altar"){
let ultima = document.getElementById('ultima_charge');
if (ultima.value != 100){
window.alert("Ultima not charged!");
}else{
SupremeAltar()
}
}
else if (btn1.innerHTML == "Radiant Supernova"){
let ultima = document.getElementById('ultima_charge');
if (ultima.value != 100){
window.alert("Ultima not charged!");
}else{
RadiantSupernova()
}
}else if (btn1.innerHTML == "Thousand Men"){
let ultima = document.getElementById('ultima_charge');
if (ultima.value != 100){
window.alert("Ultima not charged!");
}else{
ThousandMen()
};
};
})
};
});
});
});
};
}));

My tic tac toe game (jquery) is not working properly. Lost Part is not working properly

The 'Win' and 'Draw' parts are showing up on time, but the 'Lost' part doesn't show the message 'you lost'until I click on an empty cell once again. Please check out my code and help me find any errors.
Below is my code:
Marked is a class that changes the opacity of the clicked cell.
1,2,3...are the id's of respective cells in the table(html).
I tried delay() too instead of setTimeout(), but it didn't work as well.
$(document).ready(function() {
var timer;
var x = 0;
$("td").click(function() {
if($(this).text()=='') {
$(this).text("0").addClass("marked");
x = 1;
}
}).click(function() {
if(x==1) {
timer = setTimeout(function() {
var choose = $("td").not(".marked");
var random = choose[Math.floor(Math.random()*choose.length)];
$(random).text("X").addClass("marked");
},1000);
x=0;
showResult();
}
});
function showResult() {
var one = $("#1").text();
var two = $("#2").text();
var three = $("#3").text();
var four = $("#4").text();
var five = $("#5").text();
var six = $("#6").text();
var seven = $("#7").text();
var eight = $("#8").text();
var nine = $("#9").text();
if(one==two && two==three)
result(one)
else if (four==five && five==six)
result(four)
else if(seven==eight && eight==nine)
result(seven)
else if (one==four && four==seven)
result(one)
else if (two==five && five==eight)
result(two)
else if (three==six && six==nine)
result(three)
else if (one==five && five==nine)
result(one)
else if(three==five && five==seven)
result(three);
else {
var z = $("td").not(".marked");
if(z.length == 0) {
$("p").text("Draw!");
$("td").removeClass("marked");
$("td").text("");
$("#demo1").append('<img src="https://media.tenor.com/images/54c63f726505bfdb455eb4c29e626ad8/tenor.gif">');
clearTimeout(timer);
}
}
}
function result(y) {
var result = y;
if(result=="X"){
clearTimeout(timer);
$("p").text("You Lost!");
$("td").removeClass("marked");
$("td").text("");
$("#demo1").append('<img src="https://media.tenor.com/images/08902a85a6107684f8614846f4a54218/tenor.gif">');
}
if(result=="0") {
$("td").text("");
$("p").text("You Won!");
$("#demo1").append('<img src="https://i.gifer.com/4OuC.gif">');
$("td").removeClass("marked");
clearTimeout(timer);
}
}
});
You are calling showResult immeadiately when the user clicked, so it cant't recognize the X put into the table one second later.
Just do:
$("td").click(function() {
[...]
}).click(function() {
if (x == 1) {
timer = setTimeout(function() {
var choose = $("td").not(".marked");
var random = choose[Math.floor(Math.random() * choose.length)];
$(random).text("X").addClass("marked");
/******** ADD ANOTHER CHECK HERE ********/
showResult();
}, 1000);
x = 0;
showResult();
}
});
It might also be a good idea to add a return to showResult that returns false when a result was achieved. This way you could do something like
x = 0;
if (showResult()) {
timer = setTimeout(function() {
[...]
}
}
And the user can't get a loose message right after a win message.
Also: Why do you need the 2 click listeners? You can just use the if statement in the top one and then you don't need the (x == 1)

jQuery not responding to timed events

Im having trouble getting my second function to react to the changes the first function brings.
var jumbotron = function(){
var jumbotronCounter = 1
var jumbotronSwitch = function(){
var jumbotronTimer = function(){
jumbotronCounter++
}
jumbotronTimer();
if (jumbotronCounter > 3){
jumbotronCounter = 1
}
console.log(jumbotronCounter);
}
setInterval(jumbotronSwitch,7000);
var jumbotronListener = function(){
if(jumbotronCounter = 1){
console.log('first');
}else if(jumbotronCounter = 2){
console.log('second');
}else if(jumbotronCounter = 3){
console.log('third');
}
};
jumbotronListener();
}
jumbotron();
Id like to use "jumbotronListener" to run some code when "jumbotronCounter" changes
jumbotronListener is indeed only running once. You can, instead, run it every time the interval runs:
var jumbotron = function () {
var jumbotronCounter = 1;
var jumbotronSwitch = function () {
var jumbotronTimer = function () {
jumbotronCounter++;
};
jumbotronTimer();
if (jumbotronCounter > 3) {
jumbotronCounter = 1;
}
// Execute the listener every time the interval runs
jumbotronListener();
console.log(jumbotronCounter);
};
setInterval(jumbotronSwitch, 7000);
// Run for the first time if you wish:
jumbotronListener();
// Set this as function so you can 'use it before declaring it'
function jumbotronListener() {
// You had invalid operators. = assigns and === compares (strictly)
if(jumbotronCounter === 1) {
console.log('first');
} else if(jumbotronCounter === 2) {
console.log('second');
} else if(jumbotronCounter === 3) {
console.log('third');
}
}
};
jumbotron();
You also had some missing semicolons in there, sometimes it's not a problem since JavaScript auto-inserts them, but sometimes it is, so it's a good idea to always make sure to manually insert them where they go.

Javascript executes both if and else

Here's my code:
var srcArray = ["_images/overlook.jpg","_images/winery_sign.jpg","_images/lunch.jpg","_images/bigSur.jpg","_images/flag_photo.jpg","_images/mission_look.jpg"];
var myImg = document.getElementById("mainImage");
var imgIndex = 0;
var status = false;
myImg.onclick = function () {
if (status) {
var collage = setInterval(changeSrc,1500);
status = true;
} else {
clearInterval(collage);
status = false;
}
}
function changeSrc (){
myImg.setAttribute("src",srcArray[imgIndex]);
imgIndex++;
if (imgIndex == srcArray.length) {
imgIndex = 0;
}
}
What I'm trying to do is to set interval on changeSrc when interval is not set and clear interval when interval is set. I saw in Firebug that browser executes first part of if and then executes second line of else (status = false).
Once interval is set when I click on image it starts another interval on the same image. It basically just runs faster with every click and doesn't stop.
Where's the problem?
Thanks in advance for your help :)
Do this:
myImg.onclick = function () {
if (status) {
var collage = setInterval(changeSrc,1500);
} else {
clearInterval(collage);
}
status = !status;
}
In your code, you are initializing status incorrectly
Just move collage var out of if statement because when you declare it into if statement this variable only will exist in this scope.
And I don't know why it don't work with bool that's why I change it to number :P I hope someone else can answer that.
var myImg = document.getElementById("mainImage");
var imgIndex = 0;
var status = 1;
var collage;
myImg.onclick = function ()
{
if(status == 1)
{
collage = setInterval(changeSrc,1500);
status = 0;
}
else
{
clearInterval(collage);
status = 1;
}
}
When you click the image it starts the images rolling over, instant for first, than per timer if you click it stops. I assume that is the desired effect. You don't need the status.
var srcArray = ["_images/overlook.jpg","_images/winery_sign.jpg","_images/lunch.jpg","_images/bigSur.jpg","_images/flag_photo.jpg","_images/mission_look.jpg"],
myImg = document.getElementById("mainImage"),
imgIndex = 0,
tmr;
myImg.onclick = function () {
// if tmr === undefined, start the rollover.
if (!tmr) {
// I call changeSrc() to give instant feedback on first click!
changeSrc();
tmr = setInterval(changeSrc,1500);
// else if tmr has a value stop the rollover, make sure we set tmr to undefined.
}else{
clearInterval(tmr);
tmr=undefined; !IMPORTANT
}
}
function changeSrc (){
myImg.setAttribute("src",srcArray[imgIndex]);
imgIndex++;
if (imgIndex == srcArray.length) {
imgIndex = 0;
}
}
http://jsfiddle.net/uq8mfLun/2/
Change the status in function changeSrc() instead of doing it in if else.
Your code works pretty well. You have to change:
if (status)
by
if (status == true)
also
if (status === true)
Explanation: If you write if(status === true), the result will be true only if status is true. But if you write if(status), the result will be true for any status that is different from false, null, empty string, undefined value, or 0.
Hope it useful!

Categories

Resources