How To Select Next 'n' Consecutive Elements On Every Click Using Jquery?
How to select next 'n' consecutive elements on every click using jQuery? In below example, I want to select the first 4 li elements on first button click, next 4 on 2nd click and n
Solution 1:
You can create a variable initialized to 0
and increment the variable by 4
, use .slice()
to select n elements
$(document).ready(function(){
var n = 0;
$(".btn").on('click', function(){
$("li")
.removeClass("selected")
.slice(n, n += 4)
.addClass("selected");
if (n >= $("li").length) n = 0;
});
});
.btn{ text-decoration:none; background:blue; color:#fff; padding:5px; border-radius:4px;float:left;}
ul{ list-style:none;float:left;clear:both;}
ulli{ padding:5px;background:#555; color:#fff; float:left; border-radius:2px; margin:2px; }
.selected{ background:red;}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script><aclass="btn">select next 4 consecutive elements</a><ul><li> 1st 4</li><li> 1st 4</li><li> 1st 4</li><li> 1st 4</li><li> 2nd 4</li><li> 2nd 4</li><li> 2nd 4</li><li> 2nd 4</li><li> 3rd 4</li><li> 3rd 4</li><li> 3rd 4</li><li> 3rd 4</li></ul>
Post a Comment for "How To Select Next 'n' Consecutive Elements On Every Click Using Jquery?"