JavaScript prompt in function not saving value -


i have div that, when tapped, calls onclick function called door(). prompt comes up, , when user types prompt, goes away.

i made if statement saying: if variable (i) greater 3 (which happens when user clicks div again after typing prompt) alert user typed in prompt.

my problem comes when user re-clicks div. alert pops saying value of prompt says "undefined" instead of user entered. why?

here's code:

<!doctype html>  <html>     <head>         <style>             #mainwall{position: absolute; width: 98%; height: 98%; border: 3px solid brown; }             #door{position: absolute; left: 49%; width: 5%; height: 10px; background: green; bottom: 1%;}             #widthcorridor{position: absolute; width: 5%; height: 98%; left: 49%; background: red; bottom: 18px;}             #maincorridor{position: absolute; width: 98%; height: 5%; left: 1%; background: red; bottom: 50%;}         </style>     </head>     <body>         <div id="mainwall"></div>         <div id="maincorridor"></div>         <div id="widthcorridor"></div>         <div id="door" onclick="door()"></div>            <script type="text/javascript">             var = 1;              function door() {                 while (i == 1){                     var door = prompt();                     i++;                 }                  i++                 if (i > 3) {                     alert(door);                 }               }           </script>     </body> </html> 

let's step through code.

the first time call door():

var = 1; 

was set globally, value of i 1 when door called

function door() { 

the variable door declared here due hoisting.

    while (i == 1){ 

at point, while loop entered, because i has value of 1

        var door = prompt(); 

the user can enter value, , long press "ok" string value returned. if press "cancel", null returned.

        i++; 

the value of i becomes 2

    }     i++ 

the value of i becomes 3

    if (i > 3) { 

as 3 not greater 3, if block skipped, , function ends. value of door scoped function dumped garbage collector.

        alert(door);     } } 

now second time call door()

function door() { 

the variable door declared here, again due hoisting. declaration brings value of undefined.

    while (i == 1){ 

i retains value of 3 because it's in global scope, while loop never entered.

        var door = prompt();         i++;     }     i++ 

the value of i becomes 4.

    if (i > 3) { 

4 greater 3 body of if statement entered.

        alert(door); 

the value of door variable alerted. never initialized, retains value of undefined declaration.

    } } 

the function ends , garbage collector collects door variable again.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -