Reputation: 13
I have a click event firing on a certain amount of div's ( with class name .sqrBtn ) i only need two of these divs to display selected at a given time. How can i get the rest of the div's not selected unclickable?
My code so far: http://jsbin.com/ucuha3/110/edit
Upvotes: 1
Views: 778
Reputation: 18233
jsFiddle Demo
Define a variable in the outer scope of wherever you define your click handler and increment it each time the handler is triggered, removing the listener once you have reached the desired number of clicks.
var bol = 0;
$(".sqrBtn").click(function () {
bol++;
if (bol >= 2) {
$(".sqrBtn").off('click');
}
});
Upvotes: 4
Reputation: 1666
$(".sqrBtn").click(function () {
if($(".sqrBtn.clicked").length < 2 && !$(this).hasClass('clicked')){
$(this).addClass("clicked");
}
});
If you click the div you add the class clicked and if the total count of the divs is 2 you do nothing.
Upvotes: 0
Reputation: 33661
You can do it like this - by checking the length of the selected divs
$(".sqrBtn").click(function () {
var bol = $(".sqrBtn.selected").length < 2;
// if less less than two selected or current one is selected
if(bol || $(this).is('.selected')){
$(this).toggleClass('selected');
}
});
Upvotes: 0