Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I change picture on opening & closing details/summary?

This is my first JavaScript ever. It took lots of time but can’t get it to work.

Obviously, what it should do is changing the picture when the ‘details/summary’ part is opened. FYI it’s a follow-up from this problem that I’m trying to solve. Anyone see what I’m doing wrong?

<body>
  <script type="text/javascript">
    function changeImage(a) {
      document.getElementById("img").src = a;
    }
    details.addEventListener("toggle", event => {
      if (details.open) {
        changeImage("https://via.placeholder.com/50/ff0000");
      } else {
        changeImage("https://via.placeholder.com/50/0000ff");
      }
    });
  </script>

  <details>
    <summary>
      <table>
        <td width="64">#910</td>
      </table>
    </summary>
    <table>
      <td width="64">#910</td>
    </table>
  </details>

  <img id="img" src='https://via.placeholder.com/50'>
</body>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

That is your missing part: const details = document.querySelector('details'). Then it would work.

    function changeImage(a) {
      document.getElementById("img").src = a;
    }
const details = document.querySelector('details')
    details.addEventListener("toggle", event => {
      if (details.open) {
        changeImage("https://via.placeholder.com/50/ff0000");
      } else {
        changeImage("https://via.placeholder.com/50/0000ff");
      }
    });
<body>
  <script type="text/javascript">

  </script>

  <details>
    <summary>
      <table>
        <td width="64">#910</td>
      </table>
    </summary>
    <table>
      <td width="64">#910</td>
    </table>
  </details>

  <img id="img" src='https://via.placeholder.com/50'>
</body>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading