How to get which item was clicked?
In my html , I have a simple div :
<div id="myDiv">
....
</div>
I also set the onlick event to window.clickas follows:
window.onclick = function()
{
// do something
}
So, if I click somewhere in the div , how can I find that this click was made inside "myDiv"
Note. I can not add click event on my div, it is generated randomly from jqgrid
I add this only to clarify the discussion with @Nishit Mahetarespect to my response to my vote.
- . " , div". , , !:)
jQuery, @erkaner . , .
$(document).on("click","#myDiv", function (event) {
// Do something
});
:
- jQuery. "" , , .
document.- ,
document, /. - .
body, ( , ). - (
click) (.. ). - jQuery (
#myDiv) . . - , .
, ( ).
, ( 50 000 ), "" . .
onclick=
- -,
window.onclick- , - , ( , jQuery, ). - -, ,
onclick, ( , ). , jQuery , :)
:
, -, . , " div ", HTML :
$(document).on("click","table div", function (event) {
// Do something
});
:
http://jsfiddle.net/TrueBlueAussie/eyo5Lnsy/
@Sashi Kant: HTML (, ), :)
addEventListener - jQuery
document.getElementById('myDiv').addEventListener('click',function(e){
// this div has been clicked
console.log('this div has been clicked');
});
UPDATE
-jQuery-
document.addEventListener('click',function(e){
if( e.target.id == 'myDiv' )
{
// this div has been clicked
console.log('this div has been clicked');
}
});
check the code below. check out demo
use event.target to get the clicked element.
window.onclick = function(event)
{
if(event.target.id == "myDiv"){
alert("here")
}else{
alert('Body')
}
console.log(event.target.id)
}