Skip to content Skip to sidebar Skip to footer

Trying To Make A Div Appear When A Button Is Clicked

Here is the code , first of all why is the div showing up when I set it's display value to 'none'; and is there anythign I else I need to fix to make the div appear when I click th

Solution 1:

Don't use inline javascript - attach an event listener instead and make sure to place your code either in window.onload = function() {} or right before the closing </body> tag. That way your elements will be found when the script runs. Try this code:

HTML:

<button id="btn">Try it</button>

<div id="test">
</div>

JS:

document.getElementById("test").style.display ="none";

functionopenTest() {
    document.getElementById("test").style.display = "block";
}

document.getElementById('btn').addEventListener('click', openTest);

Solution 2:

As mmm already noted, the main problem is the order of execution of your fiddle and, possibly, your real code.

Basically the HTML was parsed before the JS executed, so first of all, openTest was not found yet. Then, when your JS is parsed, openTest is defined, but it is likely that your code is actually wrapped in a function to not leak globals. In the result, openTest is not accessible again.

Fixing it could be as simple as that: https://jsfiddle.net/6092dquv/18/ - exposing the openTest function explicitly binding it to the global window object by changing function openTest() { to window.openTest = function() {

But it is a bad practice, you leak a global and you mix presentation and logic (HTML and JS) in your HTML.

So the good pratice is as in the aforementioned answer: grab your button, assign the handler, and do your logic in one place - in JS. If possible, the button should be a regular form handled server-side if the user doesn't have JS (it doesn't mean he disabled it - it means, for example, the JS file is still loading for him!), or if that's not an option, insert the button programatically from JS as well, so he never sees a thing that doesn't work.

Post a Comment for "Trying To Make A Div Appear When A Button Is Clicked"