Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to know if an element is already clicked jquery

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?

like image 239
Sadiksha Gautam Avatar asked Jul 27 '11 09:07

Sadiksha Gautam


3 Answers

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/

like image 134
Gabriele Petrioli Avatar answered Oct 14 '22 11:10

Gabriele Petrioli


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

like image 36
Steve Avatar answered Oct 14 '22 10:10

Steve


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. 
});
like image 35
JohnP Avatar answered Oct 14 '22 11:10

JohnP