Doesn't look random to me unless $Statss (is that a typo, did you mean $States ?) is already made random on the server side. Though random with 3 items isn't a big deal, it will be the same order more often than not most likely. This code will not do what you say it does:
Code:
var newtext = 'img[Num]';
document.myform.outputtext.value = newtext;
It will output the literal string assigned to newtext, not any image name. To arbitrarily assume the array length will be 3 is questionable. There is a lot of global exposure, only the function name need be exposed globally, actually not even that, but the code involved to eliminate it from the global scope is perhaps not justified here. The innerHTML property is non-standard, and really unnecessary here. Both rows and cols are required for a valid textarea tag, you could probably do with a text input here. For strict validation, inline elements should be inside block level elements other than the body tag or forms, your td tags were completely invalid - no table. But the real issue, the answer to your main question is that when the code runs the first time, the output textarea doesn't exist yet.
Now, the least amount of code packed together as tightly as possible isn't always the best thing, almost never is. Efficiency in execution and preservation of the global scope are both more important. Scripts may always be minified and made external later if you want packed code, but only if they are written clearly and properly to begin with.
So, though probably not perfect, and not even tested, this shows a big improvement in all or at least most of the points I mentioned:
Code:
<div>
<img id="img" src="" style="width:135px; height:135px; visibility: hidden;" alt="">
</div>
<div>
<br><br><button onclick="newi();">different image</button>
</div>
<form name="myform">
<div><textarea name="outputtext" cols=30 rows=1></textarea></div>
</form>
<script type="text/javascript">
function newi(){
if(newi.Num > newi.ar.length - 1){
newi.Num = 0;
newi.img.src = 'images/screenshots/' + newi.ar[newi.Num];
}
else{
newi.img.src = 'images/screenshots/' + newi.ar[newi.Num];
}
newi.output.value = newi.ar[++newi.Num];
}
newi.Num = 1;
newi.ar = new Array(<?php echo "$Statss"; ?>);
newi.img = document.getElementById('img');
newi.output = document.forms.myform.elements.outputtext;
newi.img.onload = function(){
newi.img.style.visibility = 'visible';
newi.img.onload = null;
}
newi();
</script>
If there are any problems with it executing properly, which is possible because it is untested, they should be easy enough to work out.
Notes: All of the above remarks are directed at the original code. I have not looked in detail at Vic's code. The markup assumes a valid page to HTML 4.01 strict. The image tag should be given a default source attribute then its style should not include visibility hidden, and this bit may be dropped:
Code:
newi.img.onload = function(){
newi.img.style.visibility = 'visible';
newi.img.onload = null;
}
Bookmarks