0

I'm trying to make a div appear and disappear using javascript, but it's not working.I've included the javascript file(where the function is),but I don't understand why it's not working.

When I press the button, nothing happens.

HTML code:

<script type="text/javascript" src="show_on_click.js"></script>

<div id="myDiv" style="display:none" class="answer_list">Button Test</div>
<input type="button" name="answer" onclick="ShowDiv()" value="Test"/>

JavaScript code:

function ShowDiv(){
    document.getElementById("myDiv").style.display = 'block';
}
nikamanish
  • 662
  • 4
  • 17
Ioan Andrei
  • 93
  • 1
  • 16
  • Do you have errors in your JS console? Are you sure your function `ShowDiv` is called when you click on the button? – sjahan Dec 08 '17 at 10:43
  • 1
    Have you checked your browser console for errors? – NewToJS Dec 08 '17 at 10:43
  • You need to put the script after the button - what does "html and body tags are open in the header" mean? Press F12 and see that you get ShowDiv is not defined – mplungjan Dec 08 '17 at 10:43
  • Your code is only making it to visible, first check whether is visible, if visible, then hide. if hidden then make it visible. https://www.w3schools.com/howto/howto_js_toggle_hide_show.asp – Chidambaram Dec 08 '17 at 10:48
  • You also want to toggle the display – mplungjan Dec 08 '17 at 10:48
  • Possible duplicate of https://stackoverflow.com/questions/21070101/show-hide-div-using-javascript – Chidambaram Dec 08 '17 at 10:49
  • @sjahan, the function it's not even called.I've tried to display a text instead the style.display just to be sure, but it's not working. – Ioan Andrei Dec 08 '17 at 10:53
  • @Chidambaram I will check the link and i will come back with a reply.Thank you! :) – Ioan Andrei Dec 08 '17 at 10:55

2 Answers2

2

Try this:

<div id="myDiv" style="display:none" class="answer_list">Button Test</div>
<input type="button" name="answer" onclick="ShowDiv()" value="Test"/>

<script>
  function ShowDiv(){
    document.getElementById("myDiv").style.display = 'block';
  }
</script>


There are one or both of two errors:

  • your src path for script is wrong
  • somewhere you redefine function for button
Turar Abu
  • 368
  • 1
  • 3
  • 11
1

Another problem will be: you are only set display to block, not to none again.

Try this:

function ShowDiv() {
    var element = document.getElementById("myDiv");
    if (element.style.display === 'none') {
        element.style.display = 'block';
    } else {
        element.style.display = 'none';
    }
}