I'm not sure why this is happening. I thought javascript execution was fairly straightforward, but it appears a line of code I have is being skipped. Here's the codepen for it.
Basically, when I click a check box I want an invisible <div>
to become visible then go back to invisible. Somehow its being skipped. I added a long loop to make sure it wasn't just disappearing super fast without a flash but.. i don't know.
function change_state(chx) { alert('in'); if (chx.checked) { alert('hey its checked'); $('#divWait').css('display', 'table'); // this <div> never shows up DoStuff(); $('#divWait').css('display', 'none'); } else { alert('not checked'); } } function DoStuff() { var x = 0 while (x < 1000000) { x = x + 1; } alert(x); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div style="color: white;"> Change Div State <input onchange="change_state(this)" type="checkbox" value="something" id="btnState" /> </div> <div id="divWait" style="width: 200px; height: 50px; background-color: blue; color: yellow; display: none;"> What the eff??? </div>
Thanks for the help.
As @NikosM pointed out in his comment, you should use setTimeout() to invoke a piece of code after some delay. Using a loop wouldn't help in what you are trying to achieve for 2 reasons:
Solution:
Wrap the code to hide your div
within setTimeout()
and specify the delay in milliseconds .
function change_state(chx) { console.log('in'); if (chx.checked) { console.log('hey its checked'); $('#divWait').css('display', 'table'); // this <div> never shows up setTimeout(function() { console.log('hiding div'); $('#divWait').css('display', 'none'); }, 3000); // Specify timeout in milliseconds } else { console.log('not checked'); } }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div style="color: white;"> Change Div State <input onchange="change_state(this)" type="checkbox" value="something" id="btnState" /> </div> <div id="divWait" style="width: 200px; height: 50px; background-color: blue; color: yellow; display: none;"> What the eff??? </div>
Notice that I have replaced alert()
with console.log()
to remove annoying alert boxes.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.