-1

I need help with my code. I have tried to make a code but this won't work. could someone please try to help. I can't tell what it is!

    if (document.getElementById("killer").style.marginLeft > 
        document.getElementById("player").style.marginLeft) {
        alert("1");
    };
    if (document.getElementById("killer").style.marginLeft < 
        document.getElementById("player").style.marginLeft) {
        alert("2");
    };

Please help me!

Next Day...

Thank you guys for trying to help but I managed to get it done. I am very happy to see that so many people are willing to help new coders or just coders in need! I have just entered the community and I am very excited. This is the code.

    setInterval(function (killer) {
        if (document.getElementById("killer").style.marginLeft > 
            playerPositionX) {
            alert("success!")
        };

        if (document.getElementById("killer").style.marginLeft < 
            playerPositionX) {
            alert("error!")
        };
    }, 3000);

Hope it helps someone else in need.

  • 4
    What is happening vs what do you expect to happen? And if the alerts aren't showing, then your conditions aren't true. Debug to find out why. And are there any errors in the console? – Carcigenicate Sep 02 '17 at 12:06
  • check this, how to get [marginLeft value](https://stackoverflow.com/q/14275304/3551786) – Durga Sep 02 '17 at 12:07
  • Did you notice that you're comparing strings? – Bergi Sep 02 '17 at 14:16

1 Answers1

0
var killer = document.getElementById("killer");
var player = document.getElementById("player");
if (getComputedStyle(killer)['marginLeft']) > getComputedStyle(player)['marginLeft'])) {
    alert("1");
}else{
    alert("2");
}

When you get style, you should use getComputedStyle(elementName)[attributeName]

When you set style, elementName.style.attributeName = anything

kyun
  • 9,710
  • 9
  • 31
  • 66
  • I am making this code for HTML so I don't know if this will work how it is supposed to? marginLeft is the CSS style for margin-left. you have it as a string, I am probably wrong considering I am a super new and armature coder. – Bailey Moir Sep 02 '17 at 21:09