I have this piece of Javascript and it just won’t work. I allready checked JSlint but that said everything works. Still doesn’t work. The javascript is located not in the HTML but is linked in the <head>
note: I am working with a local server, so pageload in instant.
function changeVisibility() { var a = document.getElementById('invisible'); a.style.display = 'block'; } var changed = document.getElementById('click1'); changed.onchange = changeVisibility;
This here is the corresponding HTML
<input type='file' name='click[]' size='35' id='click1' /> <div id='invisible' style='display: none;'> <a href='javascript:addFileInput();'>Attach another File</a> </div>
So what happens is I click on the input, select a file and approve. Then then onchange event triggers and the style of my invisible div is set to block.
Problem is, I keep getting this error:
‘changed is null: changed.onchange = changeVisibility;’
i don’t get it, I seriously don’t get what I’m overlooking here.
EDIT: question answered, thank you Mercutio for your help and everyone else too of course. Final code:
function loadEvents() { var changed = document.getElementById('click1'); var a = document.getElementById('invisible'); document.getElementById('addField').onclick = addFileInput; changed.onchange = function() { a.style.display = 'block'; } } if (document.getElementById) window.onload = loadEvents;
This here is the corresponding HTML:
<input type='file' name='click[]' size='35' id='click1' /> <div id='invisible' style='display: none;'> <a href='#'>Attach another File</a> </div>
Also, thanks for the link to JSbin, didn’t know about that, looks nifty.
This sounds like the DOM object doesn’t exist at the time of referencing it. Perhaps change your code to execute once the document has fully loaded (or place the javascript at the bottom of your page)
that’s not the issue – the constituent parts of a document are loaded in order. It doesn’t matter how fast they are loaded, some things happen before others 😀
Place an id on there, and inside your function do this:
Or, as you already have the div as the variable ‘a’:
But this obviously leaves you with an invalid anchor tag. Best practice suggests that you should provide a way to do it without javascript, and override that functionality with your javascript-method if available.