I’ve coded with javascript a lot in the past, so it’s particularly frustrating when I stare at something as simple as this for hours and just can’t figure out why it won’t work. Can someone tell me why this code is completely unresponsive?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var passCode = 0;
function oneFunc()
{
passCode = 1;
}
function oneFunc()
{
passCode = 2;
}
function oneFunc()
{
passCode = 3;
}
function oneFunc()
{
passCode = 4;
}
if(passCode == 1)
{
if(passCode == 2)
{
if(passCode == 3)
{
if(passCode == 4)
{
window.location.href = 'frompassCode.html';
}
}
}
}
</script>
<title> </title>
</head>
<body>
<button onclick="oneFunc()">Button1</button><br/>
<button onclick="twoFunc()">Button2</button><br/>
<button onclick="threeFunc()">Button3</button><br/>
<button onclick="fourFunc()">Button4</button><br/>
</body>
</html>
If my logic is off, I can deal with that, but it won’t do anything. I put an alert inside the functions to get it to move, but nothing. I’m sure this problem must be simple…
Other than the fact that oneFunc() is declared multiple times and the logic of the if statements will never work, the fact that Javascript is interpreted linearly is the problem. If you look at the code:
This code is executed as the HTML document is loaded into the browser. First, it sets the variable passCode to 0. Then it goes through (and probably has problems) declaring all the functions. Then it goes through the if statements and executes them, because they’re not in a function. Any Javascript code not in a function is executed immediately and linearly down the page. That means your if statements will never be executed again. You can click on the buttons all you want, they will obviously change the value of passCode, but the if statements will never be executed again because they are global code. You’d probably have to put the if statements in a new function, and always call that function after the oneFunc() calls.