Reputation: 341
I'd like to allow user click once in each link only. This is to avoid further problems with tabs and other stuff, and to keep the control over the system I'm working on.
So, I tried to use "one" method, but not seems to work, only the alert I've putted in:
$(window).load(function(){
$('.lockit').one('click', function(){alert('you cannot click here again'); } );
});
Any idea about how to proceed? I'm using JQuery 1.8.1.
Thanks in advance.
Upvotes: 1
Views: 75
Reputation: 1533
Assuming you only have one link which needs to be blocked,
$(document).ready(function() {
var clicked = false;
$(".block-link").on('click', function(e) {
if(clicked) {
e.preventDefault();
alert('You can only click once');
} else {
clicked = true;
}
});
});
Otherwise if you want to do this for every link with class .blocked-link
,
$(document).ready(function() {
$(".blocked-link").each(function() {
// Set initial data attribute
$(this).data('clicked', 0);
$(this).on('click', function(e) {
if($(this).data('clicked') == 1) {
e.preventDefault();
alert('You can only click this link once');
return false;
} else {
$(this).data('clicked', 1);
}
});
});
});
jsFiddle for multiple links: http://jsfiddle.net/3C63m/
EDIT: Include custom onClick functions
$(document).ready(function() {
$(".blocked-link").each(function() {
// Set initial data attribute
$(this).data('clicked', 0);
$(this).on('click', function(e) {
if($(this).data('clicked') == 1) {
e.preventDefault();
alert('You can only click this link once');
return false;
} else {
$(this).data('clicked', 1);
/* PLACE YOUR onClick ACTIONS HERE */
}
});
});
});
Upvotes: 1
Reputation: 16942
You can add a class to it when it is clicked. Then check if it has the class when clicked. If so do not show alert.
$('.lockit').click(function(e){
var aTag = $(this);
if(aTag.hasClass('clicked'))
return false;
alert('you cannot click here again')
aTag.addClass('clicked')
});
Upvotes: 0
Reputation: 2570
You could try .preventDefault function.
var count = 0;
$('.lockit').one('click', function( event ){
alert('you cannot click here again');
count++;
if ( count > 0 ) {
event.preventDefault;
}
});
});
Upvotes: 1
Reputation: 197
Give this a shot:
$('.lockit').on('click', function(){
alert('you cannot click here again');
$(this).unbind('click');
});
Upvotes: 0