Search code examples
javascriptfunctioncomparison-operators

Why is this function youWin not working properly?


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

Solution

  • 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();
      });
    });