I'm stuck with a probobaly simple problem, but i'm very new to javascript and just can't figure it out. I have a link that shall hide/show a div. I have this code, whitch works well. window.onload=initAll; function initAll(){ document.getElementById("rediger_id1").onclick=openEdit; } function openEdit(){ if(document.getElementById("id1").style.height!="auto"){ document.getElementById("id1").style.height="auto"; } else if(document.getElementById("id1").style.height=="auto"){ document.getElementById("id1").style.height="0px"; } return false; } Code (markup): I need to do this to alot of elements on the page with a for loop. So i try to pass "id" as an argument to "openEdit". This is where things get wierd. Somehow the div gets visible right after the page loads, and the link doesent work. window.onload=initAll; function initAll(){ document.getElementById("rediger_id1").onclick=openEdit("1"); } function openEdit(id){ if(document.getElementById("id"+id).style.height!="auto"){ document.getElementById("id"+id).style.height="auto"; } else if(document.getElementById("id"+id).style.height=="auto"){ document.getElementById("id"+id).style.height="0px"; } return false; } Code (markup): I realy hope someone can help me get on with my learning. Thanks alot.
It's because you're actually calling the function openEdit("1") in the init. Try using function {openEdit("1")}; document.getElementById("rediger_id1").onclick= function {openEdit("1")}; I *think* that'll work. You'll have to test it.
Just a typo - highlighted braces need to be there ... document.getElementById("rediger_id1").onclick= function[color=red]()[/color] {openEdit("1")}; Code (markup):
Thanks. That worked. Now i got one more problem. There will be several divs with id=id1, id2, id3 and so on. How many there will be is variable. I also gave all of them the class editbox so i can count how many there is. I need that to know how many times to run the for loop. As getElementsByClassName doesent work in IE i could not use that. Does anyone know a better way of counting them?
This wil be run in a loop within a function. I haven't understod closures, or how to avoid it. I end up having all the links doing the same action.