Imagine if we have some divs, and we want to show them one by one like a gallery, by providing users two buttons to navigate to previous or next div. How do we code it? In this tutorial I’ll share how I do it by using jQuery.
Watch this video:
Below is the source codes:
<!DOCTYPE html>
<html>
<head>
<title>ZK Tutorials</title>
<script src="jquery-3.3.1.min.js"></script>
<style>
.mybox{
width: 100px;
height: 100px;
border: 1px solid black;
background-color: green;
color: white;
font-size: 20px;
margin: 5px;
padding: 10px;
display: none;
}
</style>
</head>
<body>
<h1>How to hide or show previous or next div with jQuery</h1>
<div class="mybox">One</div>
<div class="mybox">Two</div>
<div class="mybox">Three</div>
<div class="mybox">Four</div>
<div class="mybox">Five</div>
<div>
<button onclick="showPrev();">Show Prev</button>
<button onclick="showNext();">Show Next</button>
</div>
<script>
var visibleDiv = 0;
function showDiv(){
$(".mybox").hide();
$(".mybox:eq(" + visibleDiv + ")").show();
}
showDiv();
function showNext(){
if(visibleDiv == $(".mybox").length-1){
visibleDiv = 0;
}else{
visibleDiv++;
}
showDiv();
}
function showPrev(){
if(visibleDiv == 0){
visibleDiv = $(".mybox").length-1;
}else{
visibleDiv--;
}
showDiv();
}
</script>
</body>
</html>