Click to See Complete Forum and Search --> : variable inside function stops second function working


ev66
09-25-2006, 02:21 PM
why is it that when the newwin variable is declared outside the myfunc() function, the closewin() function works and closes the window,
but when newwin is declared inside the myfunc(), the closewin() function does not work ?

THIS WORKS
<head><script type="text/javascript">
var newwin;
function myfunc() {
newwin=window.open("","","width=300,height=300")
}
function closewin(){
if(newwin){ newwin.close();}
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>

<body>
<input type="button" value="click me" onclick="myfunc()" />
<input type="button" value="close" onclick="closewin()" />
</body>


THIS DOES NOT WORK
<head><script type="text/javascript">
function myfunc() {
var newwin=window.open("","","width=300,height=300")
}
function closewin(){
if(newwin){ newwin.close();}
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>

<body>
<input type="button" value="click me" onclick="myfunc()" />
<input type="button" value="close" onclick="closewin()" />
</body>


thank you

jvanamali
09-25-2006, 02:56 PM
newwin declared in function cannot be used outside the function

If you declare newwin outside the function, it works through out the page,
it is similar concept of global and local variable

ev66
09-25-2006, 03:02 PM
thank you . understand now