0

I want to use the below code to add an onClick event to a button.

document.getElementById("first").addEventListener("click", changeHeight);

function changeHeight() {
    var panelH = document.getElementById('second');

    if (panelH.style.height == '') 
        panelH.style.height = '160px';
    else 
       panelH.style.height = '';
}

but just works when is wrapped inside this:

window.onload = function() {

}

What should I change in other to use that code without using window.onload event?

wario
  • 1
  • 3
  • 2
    why don't you want to put it in `window.onload`? But anyway, it probably still works without, provided you put the JS code (or the ` – Robin Zigmond Aug 07 '19 at 21:03
  • Thanks for your comment. When I use window.onload other elements (buttons) stop working. – wario Aug 07 '19 at 21:07

1 Answers1

1

It works fine - try running the code snippet below. I would guess that you have put your script tag in head rather than in the bottom of body. Thus the script is ran before there is an element with id=first. So if this is the case then just move your script tag to the bottom of body (it's where people tend to put their script tags).

document.getElementById("first").addEventListener("click", changeHeight);


function changeHeight() {
       var panelH = document.getElementById('second');

       if (panelH.style.height == '') 
           panelH.style.height = '160px'
       else 
           panelH.style.height = ''
}
#second {
  background-color: teal;
}
<button type="button" id="first">Change height</button>
<div id="second">Test</div>
Mohrn
  • 793
  • 4
  • 14