I am trying to hide/show an image when you click on a button. I wish to only use JavaScript, CSS, and HTML in this small project. The code I have so far is:
<span id = "one">
<img src = "1.png" alt = "Picture of 1" style="display: none;"/>
</span>
<input type="button" value="One" onclick="showOne();" />
<script type = "text/javascript" src= "123clickJs.js">
</script>
^ That is the HTML.
Here is the JavaScript:
function showOne() {
var img1 = document.getElementById("one");
img1.style.display = "";
if(img1.style.display == "inline" ) {
img1.style.display = "none";
}
else {
img1.style.display = "inline";
}
}
But for some reason, it is not toggling the image visible/hidden. Any ideas on what I might be doing wrong?
Hiding or showing anything is more straight forward if you simply use a class.
oneButton.onclick = function () { one.classList.toggle('show'); }
#one { display: none; } #one.show { display: block; }
<input id="oneButton" type="button" value="Toggle the image" /> <div id="one"> <img src="http://i.imgur.com/a2F7iyp.jpg" alt="Picture of 1" /> </div>
In your code, you first set img1.style.display = ""
and then check if it is inline
or none
. It will always be ""
here so the if
condition is always ignored.
Try this instead:
function showOne() {
var img1 = document.getElementById("one");
if (!img1.style.display !== "none") {
// If the image is displayed, whatever its style is, hide it
img1.style.display = "none";
} else {
// Otherwise display it
img1.style.display = "inline";
}
}
I think you can just simply use toggle()
JavaScript
$("#radio_btn").on("click", function () {
$('.img_display').toggle();
});
HTML
<span id="one">
<img class="img_display" src = "http://www.monochrome-photo.info/home/nbigeast/monochrome-photo.info/public_html/wp-content/uploads/2012/10/1349454271_apple.png" alt = "Picture of 1" style="display: none;">
</span>
<input type="button" value="One" id="radio_btn" />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.