I am having some problems in executing the following code:
var i = 1;
$('.hello:not(.selected)').on('click',function(){
$(this).addClass('selected');
console.log(i++);
});
The problem is that this code should trigger just ONE time after the class selected has added, but it is executing many times, I just want the i variable not to increase. In other words, I am trying to do the following (which works, but i don't want to use the live function since it has deprecated):
$('.hello:not(.selected)').live('click', function () {
$('.hello').removeClass('selected');
$(this).addClass('selected');
...
});
Thanks so much for your responses in advance, k
The click() method simulates a mouse-click on an element. This method can be used to execute a click on an element as if the user manually clicked on it.
The :not() selector selects all elements except the specified element. This is mostly used together with another selector to select everything except the specified element in a group (like in the example above).
To exclude first and second element from jQuery, use the slice() method.
The not() method returns elements that do not match a certain criteria. This method lets you specify a criteria. Elements that do not match the criteria are returned from the selection, and those that match will be removed. This method is often used to remove one or more elements from a group of selected elements.
Your code is taking the set of elements that currently satisfy this criteria:
$('.hello:not(.selected)')
and setting up this event handler for all eternity:
.on('click',function(){
$(this).addClass('selected');
$(this).css({opacity : 0.5});
console.log(i++);
});
Particularly important is the fact that once the handler is set on an element, it will continue to be active even if later on that element no longer satisfies the criteria (in this case, by gaining the selected
class).
There are several ways to achieve the desired behavior. One would be to dynamically check that the "filter" condition still holds inside the event handler:
$('.hello').on('click',function(){
if($(this).hasClass('selected')) {
return;
}
$(this).addClass('selected');
$(this).css({opacity : 0.5});
console.log(i++);
});
Another would be to delegate the event -- in this case, a parent element would be notified of the event on one of its descendants and it would dynamically check that said descendant satisfies the filter condition before deciding to trigger the event handler (code shamelessly pasted from Ben Lee's answer):
$('body').on('click', '.hello:not(.selected)', function() {
$(this).addClass('selected');
$(this).css({opacity : 0.5});
console.log(i++);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With