If you use ==
(or ===
) for the comparison, and always increase the counter, the alert only comes at the sixth click.
Note: Declare the variable inside the ready
event handler, it doesn't need to be a global variable.
// When button is clicked, add 1 to the variable
$(document).ready(function() {
// Declare the variable
var generic_counter = 0;
// Log the variable
console.log(generic_counter);
$(".generic").click(function() {
generic_counter++;
console.log(generic_counter);
if (generic_counter == 6) {
alert("You've been looking up a lot about GENERIC, maybe contact this group?");
}
});
});
You can also unregister the event handler using the off
method once the altert has been shown, if you don't want to continue counting:
// When button is clicked, add 1 to the variable
$(document).ready(function() {
// Declare the variable
var generic_counter = 0;
// Log the variable
console.log(generic_counter);
$(".generic").click(function() {
generic_counter++;
console.log(generic_counter);
if (generic_counter == 6) {
alert("You've been looking up a lot about GENERIC, maybe contact this group?");
$(".generic").off('click');
}
});
});
For a more generic solution you can make a plugin:
$.fn.clickUntil(cnt, message) {
var elements = this;
return this.click(function(){
if (--cnt == 0) {
alert(message);
elements.off('click');
}
});
}
Then you can easily make messages for several elements. Example:
$(document).ready(function() {
var items = [
{ selector: '.generic', name 'GENERIC' },
{ selector: '.super', name 'SuPeR' },
{ selector: '.mordor', name 'M0rd0r' }
];
$.each(items, function(i, o){
$(o.selector).clickUntil(6, 'You've been looking up a lot about ' + o.name + ', maybe contact this group?');
});
});