ZaZaKi, a web developer Between Manchester UK & Rotterdam NL. © 2015-2024.

jQuery Next and Prev element addclasses

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
.box{width:100px; height:100px; border:1px solid silver; float:left;} 
.active{background-color:red;}  
.prev, .next {float:left; margin:10px;}
.prev {clear:both;}
</style>
<script>
$(document).ready(function(){ 
    $(".next").click(function(){
       var next = $('.box-holder .box.active').removeClass('active').next('.box'); 
       if (!next.length) next = next.prevObject.siblings(':first'); 
       next.addClass('active');	
    }); 
    
    $(".prev").click(function(){
       var prev = $('.box-holder .box.active').removeClass('active').prev('.box'); 
       if (!prev.length) prev = prev.prevObject.siblings(':last'); 
       prev.addClass('active');	
   });
}); 
</script> 
</head>
<body>  
<div class="box-holder">
<span class='box active'></span>
<span class='box'></span>
<span class='box'></span>
<span class='box'></span>
<span class='box'></span> 
</div>  
<button class="prev">Prev</button> 
<button class="next">Next</button> 
</body>
</html>
Categroy:
Front-end , JQuery