Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery if its the first time element is being clicked

I need my script to do something on the first time an element is clicked and continue to do something different on click 2,3,4 and so on

$('selector').click(function() {  
//I would realy like this variable to be updated  
var click = 0;  
    if (click === 0) {  
        do this  
        var click = 1;  
    } else {  
        do this  
    }
});//end click

really I think it should rely on the variables but I can't think of how to update the variable from here on out any help would be awesome.

like image 362
Luis Avatar asked Jan 14 '11 05:01

Luis


People also ask

How do you check if the element is clicked?

To check if an element was clicked, add a click event listener to the element, e.g. button. addEventListener('click', function handleClick() {}) . The click event is dispatched every time the element is clicked.

What is '$' in jQuery?

$ is pretty commonly used as a selector function in JS. In jQuery the $ function does much more than select things though. You can pass it a selector to get a collection of matching elements from the DOM. You can pass it a function to run when the document is ready (similar to body.

What is $() in JavaScript?

The $() function The dollar function, $(), can be used as shorthand for the getElementById function. To refer to an element in the Document Object Model (DOM) of an HTML page, the usual function identifying an element is: document. getElementById("id_of_element").


2 Answers

Have a look at jQuery's .data() method. Consider your example:

$('selector').click(function() {
    var $this = $(this),
        clickNum = $this.data('clickNum');

    if (!clickNum) clickNum = 1;

    alert(clickNum);

    $this.data('clickNum', ++clickNum);
});

See a working example here: http://jsfiddle.net/uaaft/

like image 62
treeface Avatar answered Sep 28 '22 00:09

treeface


Use data to persist your state with the element.

In your click handler,

use

$(this).data('number_of_clicks')

to retrieve the value and

$(this).data('number_of_clicks',some_value)

to set it.

Note: $(this).data('number_of_clicks') will return false if it hasn't been set yet

Edit: fixed link

like image 23
Ben Avatar answered Sep 27 '22 23:09

Ben