0

This is a part of a flip coin kinda page i made the animation for the coin on css depending on the current state and the future state of the coin so with every run of the function i have to reset the coin back to the default state and then set it to the future state with the new css animation the thing is.. when i ran the code it didn't work until i added the alert("hi") line.. i have no idea why and i want to fix this because i don't want the user to click ok everytime he needs to flip the coin

var flipCoin = function () {
flips ++;
var result = 1;
if (document.getElementById("fromHeadsToHeads") !== null) {
document.getElementById("fromHeadsToHeads").id = "defaultHeads";
}

switch (result) {
    case 1 :

        if (document.getElementById("defaultHeads") !== null) {
            alert("hi")
            document.getElementById("numFlips").innerHTML = flips;
            document.getElementById("defaultHeads").id = "fromHeadsToHeads";
        }
    break;
}
  • Why do you have a switch statement? `result` will always be `1`. – 4castle Aug 06 '16 at 14:55
  • Possible duplicate of [Why does jQuery or a DOM method such as getElementById not find the element?](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – 4castle Aug 06 '16 at 14:56
  • You simply can't. As soon as you change the id, reference to object will be lost – fubbe Aug 06 '16 at 15:12
  • fyi, this is a good time to use classes. ID's are meant to be static (unchanging) while classes are perfect for this kind of thing. – SpYk3HH Aug 06 '16 at 22:02

1 Answers1

0

The problem is likely that the browser has not re rendered the DOM yet between you setting the I'd and you calling getElementById.

When you alert something the browser probably triggers a render.

There are likely much better ways of going about what you are trying to do, but to address the immediate problem of the DOM not being re rendered, you could put everything following the alert in a new anonymous function that is called by a setTimeout. Sort of like:

SetTimeout (function() {...},100). You will have to get the variable scoping right, but this should give the DOM a chance to be updated.

bruceceng
  • 1,291
  • 12
  • 21