views:

65

answers:

1

Why does the following work for onLoad, and not onClick, and what would be the solution? Thanks in advance...

<head>
    <title>Untitled Page</title>
    <LINK href=CSS/showdetails.css type=text/css rel=stylesheet />
</head>
<body OnLoad="javascript:showdetails()">

<script language=JavaScript src=js/showdetails.js type=text/javascript></script>

<div id="divResults" style="OVERFLOW: auto; HEIGHT: 480px;">
<span id="ShowResults" style="VISIBILITY: hidden">Display Results</span>
<p><input id="Button1" type="button" value="button" /></p>
</div>

<script type="text/javascript">

var btn = document.getElementById('Button1');
btn.onclick = function() {showdetails();};

function showdetails() {
    var xc = document.getElementById('ShowResults');

    var top_ul = document.createElement('ul');
    top_ul.setAttribute('className','detclass');


    var li1 = document.createElement('li');
    li1.appendChild(document.createTextNode('craig'));


    var ul2 = document.createElement('ul');
    var li2 = document.createElement('li');
    li2.appendChild(document.createTextNode('Mike'));

    ul2.appendChild(li2);


    li1.appendChild(ul2);
    top_ul.appendChild(li1);

    xc.appendChild(top_ul);

    var vis = "visible";
    xc.style.visibility = vis;
    }
</script>                 
</body>
</html>
A: 

Where in your document is this script? Is it possible that the DOM element containing Button1 is not yet loaded when this script is executed? You might try putting this in a script tag after your body, rather than in your head, or wrapping it in a function that is then executed in an onload element.

EDIT: Now that the question has code tags, I can see it is in the script tag. I still recommend wrapping it in a function and calling with onLoad, to ensure that the DOM is fully loaded before the script is executed.

wilsona
Sorry, the version without the code tag was being displayed when I wrote the above, so I did not see where you had put it. I withdraw my questions.
wilsona