How to find out if an element has already been clicked by jquery

I have a script in which I click the say #stationLink element. When I click it again, I want to know if the item has already been clicked. I tried

 var a=false; $("#stationLink").click(function(){ $(this).click(function(){ a = true }); console.log(a); }); 

I get false twice and then only true .. I think something is missing. Or is there any other way to do this?

+6
source share
7 answers

This should do what you want (including keeping the counter as I saw what you want in some kind of 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 a counter with a DOM element, and thus you can apply the same handler to several elements, since each of them will have its own counter.

demo at http://jsfiddle.net/gaby/gfJj6/1/

+9
source

You can add an attribute that you could check:

 $("#stationLink").click(function(){ $(this).attr("hasBeenClicked", "true"); }); 

I do not like to use the global var to keep whether this element has been pressed for the simple reason that if you need to track more than one element, then it can be a little dirty. I prefer the class or ass attribute, as you can see in the element whether it was pressed

+4
source

In this version, the number of clicks is recorded:

 $("#stationLink").click(function() { var clickCount = $(this).data('clickCount') || 0; if (clickCount > 0) { // clicked `clickCount` times } $(this).data('clickCount', clickCount + 1); }); 

Reset counts clicks

 $("#stationLink").data('clickCount', 0); 
+4
source

This is because you actually bind another click control to the element the first time you click on it. Just remove this handler.

 var clicked = false; $("#stationLink").click(function(){ clicked = true //Code to toggle if required. }); 
+3
source

Another variant:

 $('#stationLink').click(function(){ $(this).data('clicked', true); }); console.log($(this).data('clicked')); 

I think this is the method most used by jquery ui.

+2
source

I usually add a class named .chosen or .x_visited to

 $("#stationLink").click(function(){ $(this).addClass("x_visited") } 

You can then check this with $("#stationLink").hasClass('x_visited'); eg

+1
source
 var stationLink_clicked = false; $("#stationLink").click(function(){ console.log('Already clicked? ' + stationLink_clicked); /* do stuff */ stationLink_clicked = true; }); 
+1
source

Source: https://habr.com/ru/post/893671/


All Articles