Alex Rivera | Logout

How to do "If Clicked Else .."

Asked 2011-07-08T19:14:51.120
15

I am trying to use jQuery to do something like

if(jQuery('#id').click) {
    //do-some-stuff
} else {
    //run function2
}

But I'm unsure how to do this using jQuery ? Any help would be greatly appreciated.

Edit: I'm trying to run a function if the #id has been clicked and specifically it is has not been clicked then run the function 2 ? i.e. I need to check firstly that the #id has been clicked before running function2 ?

Edit
Report

3 Answers

29

You should avoid using global vars, and prefer using .data()

So, you'd do:

jQuery('#id').click(function(){
  $(this).data('clicked', true);
});

Then, to check if it was clicked and perform an action:

if(jQuery('#id').data('clicked')) {
    //clicked element, do-some-stuff
} else {
    //run function2
}

Hope this helps. Cheers

answered 2011-07-08T19:26:18.293
10

The way to do it would be with a boolean at a higher scope:

var hasBeenClicked = false;
jQuery('#id').click(function () {
    hasBeenClicked = true;
});

if (hasBeenClicked) {
    // The link has been clicked.
} else {
    // The link has not been clicked.
}
answered 2011-07-08T19:18:04.163
0

This is all you need: http://api.jquery.com/click/

Having an "else" doesn't apply in this scenario, else would mean "did not click", in which case you just wouldn't do anything.

answered 2011-07-08T19:17:11.310

Your Answer