Reputation: 5152
I have a scenario in which i click an element say #stationLink
. When I click it again I want to know if the element was already clicked. I had tried
var a=false;
$("#stationLink").click(function(){
$(this).click(function(){
a = true
});
console.log(a);
});
I am getting false
two times then only true
.. I think i am missing something. Or is there any other way to do it?
Upvotes: 6
Views: 3507
Reputation: 9888
This version records the number of clicks:
$("#stationLink").click(function() {
var clickCount = $(this).data('clickCount') || 0;
if (clickCount > 0) {
// clicked `clickCount` times
}
$(this).data('clickCount', clickCount + 1);
});
To reset the click count use
$("#stationLink").data('clickCount', 0);
Upvotes: 3
Reputation: 195982
This should do what you want (including keeping a counter as i have seen you want in some comment)
$("#stationLink").click(function(e){
var $this = $(this);
var clickCounter = $this.data('clickCounter') || 0;
// here you know how many clicks have happened before the current one
clickCounter += 1;
$this.data('clickCounter', clickCounter);
// here you know how many clicks have happened including the current one
});
Using the .data()
method you store the counter with the DOM element, and this way you can apply the same handler to multiple elements, since each one will have its own counter.
demo at http://jsfiddle.net/gaby/gfJj6/1/
Upvotes: 9
Reputation: 2740
Another option is:
$('#stationLink').click(function(){
$(this).data('clicked', true);
});
console.log($(this).data('clicked'));
I think this is the method most used by jquery ui.
Upvotes: 2
Reputation: 50573
You could add an attribute you could check:
$("#stationLink").click(function(){
$(this).attr("hasBeenClicked", "true");
});
I don't like using a global var to keep whether this item has been clicked for the simple reason that if you have to keep track of more than one item then it can be a little messy. I prefer the ass class or attribute as you can see on the element whether it has been clicked
Upvotes: 4
Reputation: 50019
That's because you're actually binding another click handler to the element the first time you click it. Just remove that handler.
var clicked = false;
$("#stationLink").click(function(){
clicked = true
//Code to toggle if required.
});
Upvotes: 3
Reputation: 36999
var stationLink_clicked = false;
$("#stationLink").click(function(){
console.log('Already clicked? ' + stationLink_clicked);
/* do stuff */
stationLink_clicked = true;
});
Upvotes: 1
Reputation: 2101
I usually add a class named .chosen or .x_visited to it
$("#stationLink").click(function(){
$(this).addClass("x_visited")
}
Then you can check against that with $("#stationLink").hasClass('x_visited');
for example
Upvotes: 1