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?
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/
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
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.
});
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