Kevin
Kevin

Reputation: 2688

Determine if an element was clicked?

How can I determine if an element was clicked with jQuery?

Something like $('.ele').is(':clicked');

I am stuck with jQuery 1.7.2, and what I am trying to do is force the closing of some modal elements, when anywhere in the document is clicked and one is already open.

So I've got:

$('body').on('click', function () {
    if ($('.calc-info').is(':visible') && !$('.mi').is(':clicked')) {
        $('.calc-info').fadeOut('fast');
    }
});

but it throws an error, because there is no :clicked expression

Notes

Upvotes: 1

Views: 79

Answers (3)

StormRideR
StormRideR

Reputation: 1758

Try something like this.

$('mi').on('click', function () {
$('mi').attr('rel',"clicked");
});
$('body').on('click', function () {
if ($('.calc-info').is(':visible') && !$('.mi').attr('rel')=='clicked') {
    $('.calc-info').fadeOut('fast');
}
});`

Upvotes: 0

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

Just check whether the clicked element is having the class that is to be excluded. and its just a kind of short circuit implementation. The following code will block the unnecessary dom traversal if user directly clicks on the target element.

Try this,

$('body').on('click', function (e) {
    if ($('.calc-info').is(':visible') 
    && !$(e.target).hasClass('mi') 
    && !$(e.target).parents('.mi').length) {

        $('.calc-info').fadeOut('fast');

    }
});

Upvotes: 1

adeneo
adeneo

Reputation: 318282

Do it the other way around, check if the clicked element (the event.target) matches a selector

$('body').on('click', function (event) {
    if ( $(event.target).is('.ele') ) {
        // do stuff
    }
});

In your case I'd go with

$('body').on('click', function (event) {
    if ( $('.calc-info').is(':visible') && 
         !($(event.target).closest('.mi').length)
       ) {
          $('.calc-info').fadeOut('fast');
    }
});

Upvotes: 2

Related Questions