Reputation: 9
I need to create a toogle button HIDE/SHOW. When I press it, all images on website must dissapear, and also when I press it again, all images must appear again.
Upvotes: 0
Views: 1496
Reputation: 11787
You can accomplish this easily by using JQuery :
<input id='myinput'>Click to Toggle </input>
var status = "show";
$("#myinput").Click(function() {
if (status == "show") {
$('img').hide();
status = "hide";
} else {
$('img').show();
status = "show";
}
});
With JQUERY Toggle (taking advice from the comments): JS Fiddle
$(function () {
$("button").click(function () {
$("img").toggle();
});
});
Upvotes: 1
Reputation: 3754
var imageVisible = true;
var btn = document.getElementById('your_button_id');
btn.addEventListener('click', function () {
var images = document.getElementsByTagName('img');
if (imageVisible) {
for (var i = 0; i < images.length; i++)
images[i].style.display = 'none'
imageVisible = false;
} else {
for (var i = 0; i < images.length; i++)
images[i].style.display = 'inline'
imageVisible = true;
}
});
Upvotes: 0
Reputation: 27072
Here is short code sample.
When the button is clicked, check if body
has class="hide"
or not and add/remove this class. Then in CSS are images inside a body with class="hide"
hidden.
<style>
.hide img {display: none}
</style>
<p>p</p>
<p>abc</p>
<img src="http://placehold.it/100x100">
<img src="http://placehold.it/100x100">
<button id="button">SHOW/HIDE</button>
<script>
var button = document.getElementById('button');
var body = document.body;
button.onclick = function() {
body.className = body.className == 'hide' ? '' : 'hide';
}
</script>
https://jsfiddle.net/6ajr0e01/
It's pure JS solution without frameworks, without iterations over all images in website. It should be (one of) the fastest.
Upvotes: 3
Reputation: 2060
<input type="button" value="Toggle images" onclick="$('img').toggle();" />
That's it! :-)
EDIT I didn't really notice that maybe you didn't want the solution in jQuery. Sorry.
Upvotes: 1
Reputation: 960
HTML
<button>Toggle between hide() and show()</button>
<p>This is a paragraph.</p>
JQuery
$(document).ready(function(){
$("button").click(function(){
$("p").toggle();
});
});
LINK : JSFIDDLE
Upvotes: 1
Reputation: 489
Here is a working version - taken from this answer: Remove element by tag name
<img src="#" height="100" width="100" />
<br>
<img src="#" height="100" width="100" />
<br>
<button onclick="DeleteImages()">Delete all images</button>
<script type="text/javascript">
function DeleteImages(){
var element = document.getElementsByTagName("img");
for (index = element.length - 1; index >= 0; index--) {
element[index].parentNode.removeChild(element[index]);
}
}
</script>
Upvotes: 0