I am not sure where you are calling dostuff() function, but there is one thing which need to be consider, if you want variable test to be global for the page. Then you should declare it like this.
//this one is preferd
test = 4;
or
window.test = 4;
This should work, make sure you are calling dostuff().
Edit: Solving Function Call Problem
So here is complete solution with overview of your problem.
Problem: You are calling doStuff() in document.ready() (This got called after loading the DOM) event and you are printing the value of variable when DOM is loading.
It shows Old Value because doStuff() is never got called before you printing the value in DOM.
Solution: There are two ways to achieve the desired output.
- Call
doStuff() before starts loading (Right after its declaration).
- Create a function, which do the calculation and return the value to be Print accordingly.
Solution 1:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script>
//Should be before Body tag
test = 4;
//Declaring function
function doStuff()
{
test = 8;
}
//Calling right after declarion
doStuff();
</script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
/*Here value is updated and ready to print any any where in the DOM*/
<h1><script type="text/javascript">
document.write(test);</script></h1>
</body>
</html>
Live URL to Solution 1
Solution 2:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script>
/*Should be before Body tag*/
test = 4;
function doStuff()
{
/*Changing value and returing it.*/
test = 8;
return test;
}
</script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<h1><script type="text/javascript">
/*Calling function and printing returned value*/
document.write(doStuff());</script></h1>
</body>
</html>
Live URL to Solution 2
Hope this will help, let me know if any thing else is there, if nothing Accpet as answer!!
dostufffunction?