If statement malfunctioning

I am currently using an if statement to make a div appear when another div has reached the coordinates of 525px and 50px.

First, I made a function:

function verifyThePosition (button) {

}

Next, I put the if statement checking positions:

function verifyThePosition (button) {
   if (icon.style.left == "525px" && icon.style.top == "50px") {

   }
}

now, I put in what’s it supposed to do:

function verifyThePosition (button) {
   if (icon.style.left == "525px" && icon.style.top == "50px") {
      console.log(left + "&&" + top)
      button.classList.add("show") 
   }
}

This code does not work, event if I move it to the exact positions.
What am I doing wrong.
Thanks Ahead of time,
Dimitri

Just to clarify: does the output from console.log() appear? I.e. is the if never matching, or is the problem that the div doesn’t appear as desired?

1 Like

@fire-eggs ,

The console.log() does not appear when the if statement is “triggered”. The div it’s attached to works fine, thought.

1 Like

I suggest put an else then put test commands there and see if the else commands will happen, if not, it means the entire if-else is not happening in your program.

Because, say, you are not sure whether the condition is met, the default move of the program is to go to else and execute the commands there. This is just to make sure that your if is working, it’s just returning false.

Hi @Dims09 :wave:

function verifyThePosition (button) {
   if (icon.style.left == "525px" && icon.style.top == "50px") {
      console.log(left + "&&" + top)
      button.classList.add("show") 
   }
}

Firstly, where do icon and button scopes happen?

You’re trying to access the position properties, but are querying the style properties. Dragging an element around won’t change its style properties only it’s x,y position.

I’m not sure what browsers you want to support but try something like this…

function verifyThePosition (button) { // button is passed in but icon is global?
    var position = icon.getBoundingClientRect();
    if (position.left === 525 && position.top === 50) { // no need for units here
       console.log(position.left + "px && " + position.top + "px"); //so let's output them here
       button.classList.add("show");
    }
}

(untested)

note you can use position.x and position.y here too. See here:

https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect

Hope that helps.

Cheers,
Billy :cowboy_hat_face:

2 Likes