Skip to content
Advertisement

JavaScript function will open div tag; second JavaScript function does not close it however

I have been browsing here and looking at similar problems, however none of the solutions seem to work. This is also my first posted question.

<table>
<tr class="foo" onclick="openEmail1();">...</tr>
<tr class="foo" onclick="openEmail2();">...</tr>
<tr class="foo" onclick="openEmail3();"> <!-- this opens fine-->
  <td>From: Me</td>
  <td>Subject: Why won't this work?</td>
  <td>Date:

  <div style="display: none" id="email3">..email popup..

    <div>...header box in email popup...</div>
    <div>...email body box in email popup...</div>
    <div>
      <button onclick="openForm();">Forward</button> <!-- this works fine-->
      <button onclick="closeEmail3();">Close</button> <!-- does not work-->
    </div>

  </div>
  <script>
  function openEmail3(){
    document.getElementById("email3").style.display = "block";
  }
  function closeEmail3(){
    document.getElementById("email3").style.display = "none";
  }
  </script>
  </td>
</tr>
</table>
This is just a pseudo code but I ran this and it works(or doesn’t work) exactly how mine does. I do not understand why the closeEmail function is not working.

Advertisement

Answer

Your code isn’t working because of event bubbling

I’ve updated your code to be more legible by putting your element in a var

 var div = document.getElementById("email3");

Changing your button element to this will stop the default functionality

<button onclick="closeEmail3();event.stopPropagation()">Close</button>

Run the snippet below to see it in action.

var div = document.getElementById("email3");
 
 function openEmail3(){
    if  (div.style.display === "none") {
    div.style.display = "block";
    }
    else {
    div.style.display === "none" }
  }
  
  function closeEmail3(){
    if  (div.style.display === "block") {
    div.style.display = "none";
    }
  }
<table>
<tr class="foo" onclick="openEmail1();">...</tr>
<tr class="foo" onclick="openEmail3();"> <!-- this opens fine-->
  <td>From: Me</td>
  <td>Subject: Why won't this work?</td>
  <td>Date:

  <div style="display: none" id="email3">..email popup..

    <div>...header box in email popup...</div>
    <div>...email body box in email popup...</div>
    <div>
      <button onclick="openForm();">Forward</button> <!-- this works fine-->
      <button onclick="closeEmail3();event.stopPropagation()">Close</button> <!-- does not work-->
    </div>

  </div>
  </td>
</tr>
</table>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement