Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do "If Clicked Else .."

Tags:

jquery

click

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 ?

like image 994
Tom Avatar asked Jul 08 '11 19:07

Tom


People also ask

How do I know if my 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. Here is the HTML for the examples in this article.

Does Onclick only work once?

JavaScript onclick function only works once (very simple code)


2 Answers

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

like image 151
Edgar Villegas Alvarado Avatar answered Oct 02 '22 01:10

Edgar Villegas Alvarado


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.
}
like image 44
James Long Avatar answered Oct 02 '22 00:10

James Long