Thursday 4 August 2011

‘Fun’ with JavaScript

With some on-going tinkering yesterday evening - styling the search widget on my blog - I wasted hours on a difference between how Chrome and Internet Explorer (and later, I discovered Opera) executed some JavaScript compared to Firefox. ‘Hours’ because I managed to side-track myself with the onblur event, and the problem was something far simpler. I put it down to rustiness - an accidental mixing of syntaxes - though the truth may be less kind; never mix alcohol and coding, kids.
<html>
<body>
<input name="search" type="text" size="10" /><br />
<input name="search" type="text" size="20" /><br />
<input name="search" type="text" size="30" /><br />

<script type="text/javascript">
var x = document.getElementsByName("search");
var i = 0;
for (i=0;i<x.length;i++)
  {
  document.write(x(i).size+' ');
  };
</script>

</body>
</html>
As usual it was a case of reducing the code to something more manageable. On executing the example above, Chrome (my default browser) and Internet Explorer will write out the sizes of the three text boxes, whereas Firefox will not. The reason is all to do with brackets; we use square brackets to access an entry in a nodelist, and parenthesis (rounded brackets) for the optional arguments to a function or method call. Chrome and others are effectively treating item as the default method on a NodeList object - hence the example JavaScript works, whereas FireFox isn’t - and the example JavaScript fails.

0 comments:

Post a Comment