Dazvolt
Dazvolt

Reputation: 697

Jquery - How to check which element was clicked with event target?

Is it possible to check which element was clicked with event target?

e.on('click', function(){
    if(!$(e.target) == 'input'){
        //do something
    }
});

I've tried the following construction, but it seems not to be working, same as:

e.on('click', function(){
    if(!$(e.target).is('input')){
        //do something
    }
});

I just don't know is it possible for event target to check something like that.

Upvotes: 4

Views: 13175

Answers (4)

Alex Char
Alex Char

Reputation: 33218

You have to specify where is the element you click. Let's say we have this html:

html

<div></div>

jQuery

$("body").on("click", function(e) {
     if($(e.target).is("input")) {
           console.log(e.target);
     }
});

fiddle

Pure JS

document.onclick = function(evt) {
    var evt=window.event || evt; // window.event for IE
    if (!evt.target) evt.target=evt.srcElement; // extend target property for IE
    alert(evt.target); // target is clicked
}

fiddle

Upvotes: 7

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

use document as selector and add event e as parameter to function :

$(document).on('click', function(e){
    if(!$(e.target).is('input')){
       alert('yes');
    }
});

Demo

Upvotes: 2

Jay Blanchard
Jay Blanchard

Reputation: 34416

Absolutely! Here is an example - http://jsfiddle.net/jayblanchard/h6DNa/

$('*').on('click', function(e) {
    if(!$(e.target).is('input')){
        console.log('clicked');
    }
});

Upvotes: 2

Balachandran
Balachandran

Reputation: 9637

You should pass event like e . to check the clicked element has input or not use is selector in jquery

$("selector").on('click', function(e){
    if(!$(e.target).is('input')){
    //do something
}
});

is() selector in jquery

Upvotes: 2

Related Questions