Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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.

like image 878
Dazvolt Avatar asked Dec 14 '22 21:12

Dazvolt


2 Answers

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

like image 128
Alex Char Avatar answered Apr 13 '23 01:04

Alex Char


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

like image 23
Balachandran Avatar answered Apr 13 '23 00:04

Balachandran