jQuery show hide toggle example
On this page, we will learn how to show and hide a specific image or block using jQuery. jQuery is the world’s most popular JavaScript Library. It have many predefined methods that’s make the scripting more easier. To show and hide we are going to use toggle()
method.
JS Snippet
$(document).ready(function () {
$('#show-hide').click(function () {
var img_selector = $(this).attr('href');
var img_switch = $(this);
$(img_selector).toggle(function () {
if ($(this).css('display') === 'none') {
img_switch.html('Show Image');
} else {
img_switch.html('Hide Image');
}
});
});
});
Check the full example.
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery-3.1.1.min.js"></script>
<script>
$(document).ready(function () {
$('#show-hide').click(function () {
var img_selector = $(this).attr('href');
var img_switch = $(this);
$(img_selector).toggle(function () {
if ($(this).css('display') === 'none') {
img_switch.html('Show Image');
} else {
img_switch.html('Hide Image');
}
});
});
});
</script>
</head>
<body>
<h1>jQuery show hide toggle example</h1>
<button href="#clickme" id="show-hide">Show Image</button>
<div id="clickme" style="display:none">
<img src="images/pm-modi.jpg">
</div>
</body>
</html>