Quantcast
Channel: Active questions tagged html - Stack Overflow
Viewing all articles
Browse latest Browse all 72388

Opening and closing pictures with single buttons (JavaScript)

$
0
0

I am new to JavaScript. I created this code in order to try and make buttons that will hide and show certain pictures on the page. I have 3 buttons, the first of which is supposed to run my JavaScript code in tags, the other two just have Javascript code inside them and they work fine. But they don't hide the picture once they are clicked a second time, which is why I am trying to do that for the first one if possible.

For some reason, I cannot get the first button with "open()" to work the way I want with my Javascript code. Can anyone with more experience please explain to me what I am doing wrong? Thank you in advance...

<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>switchpics</title>
</head>
<style>
</style>
<script type="text/javascript">
var btn1 = document.getElementById('1');
var btn2 = document.getElementById('2');
var btn3 = document.getElementById('3');
var display1 = btn1.getAttribute('display')
var display2 = btn2.getAttribute('display')
var display3 = btn3.getAttribute('display')

function open() {
  if (display1 === ('none')) {
      btn1.setAttribute('display', 'block');
  }  else { 
    btn1.setAttribute('display', 'none');
  }
}
</script>
<body>
    <img id="1" src="forge.PNG" style="height:320px; display:none; padding:10px">
    <img id="2" src="lizard.jpg" style="height:320px; display:none; padding:10px">
    <img id="3" src="walkway.jpg" style="height:320px; display:none; padding:10px">

  <button onclick="open()">1</button>
  <button onclick="document.getElementById('2').style.display='block'">2</button>
  <button onclick="document.getElementById('3').style.display='block'">3</button>
</body>
<footer>
</footer>
</html>

Viewing all articles
Browse latest Browse all 72388

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>