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
?
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.
JavaScript onclick function only works once (very simple code)
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
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.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With