简体   繁体   中英

How to get which element was clicked?

I have a simple div in my html as follows:

<div id="myDiv">
....

</div>

Also I have set the onlick event on the window.click as follows:

window.onclick = function()
{
    // do something
 }  

So if I click, anywhere in the div , how can I find that this click was made inside "myDiv"

Note : I cannot add the click event on my div, it is generated randomly from jqgrid

$(document).on("click","#myDiv", function (event) {
     alert(event.target.id);
});

Get the event from the function: window.onclick = function(event) then inside the function you can use it as event.target :

window.onclick = function(event)
{
    alert(event.target);
}

Here's an example using addEventListener - without using jQuery

document.getElementById('myDiv').addEventListener('click',function(e){
    // this div has been clicked
    console.log('this div has been clicked');
});

UPDATE

Here's the non-jQuery solution for dynamically created elements

document.addEventListener('click',function(e){
    if( e.target.id == 'myDiv' )
    {
        // this div has been clicked
        console.log('this div has been clicked');
    }
});

I am adding this purely to clarify a discussion with @Nishit Maheta regarding my down vote of his answer.

The aim of the question is simply this. "I wish to know when a dynamically added div is clicked". The moment you see dynamically added think delegated events! :)

As this question allows for jQuery, the answer by @erkaner is close to ideal for this situation. I just wish to explain why it is the appropriate solution .

$(document).on("click","#myDiv", function (event) {
     // Do something
});

Explanation:

  • This uses a jQuery delegated event handler . The event handling is "delegated" to a non-changing ancestor of the intended target, hence the name.
  • The chosen ancestor is document in this case.
  • You should use the closest non-changing ancestor to the target, but document is the best default if nothing else is closer/convenient.
  • Warning: Do not use body for delegated events as it has a bug (styling can cause it to not get bubbled mouse events).
  • The event ( click in this case) bubbles up to the handler element (ie document).
  • The jQuery selector (in this case #myDiv ) is then applied to just the elements in the bubble-chain . This is very efficient.
  • The supplied handler function is then just applied to any matching elements that caused the event .

The upshot of all this is that the element need not exist until event time (it does not need to exist when the event was registered ).

Further, because delegation is typically used on mouse events (and not 50,000 times a second) any speed difference between this and a "raw" event handler is negligible. The benefits far outweigh any trivial speed difference.

Regarding the other onclick= answers

  • Firstly, using the single window.onclick property is a bad idea as you stop anything else using it (not that anyone using jQuery should use it).
  • Secondly the event parameter passed to onclick is not provided by all browsers (this should be enough to stop anyone using it). There are workarounds, but jQuery was created to avoid browser workarounds :)

Notes:

If the naming is not under your control, you just need something to match on. Worst case, it could be as simple as "match any div under any table", but that will depend on your specific HTML & code:

$(document).on("click","table div", function (event) {
     // Do something
});

Here is a practical example:

http://jsfiddle.net/TrueBlueAussie/eyo5Lnsy/

@Sashi Kant: If you can provide a sample of your page HTML output (eg saved from the browser) I will be happy to cater for any variations of this you wish to put forward :)

 var myDiv = document.getElementById('myDiv'); myDiv.style.cursor = 'pointer'; myDiv.onclick = function() { //DO SOMETHING }; 

Here we go.

$('body').click(function(e) {      
  if (e.target.id == 'myDiv') {
    alert('My Div!!!!');
  }
});​

 $( "body" ).click(function( event ) { $( "#log" ).html( "clicked: " + event.target.nodeName ); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="myDiv"> .... </div> <div id="log"></div> 

check below code. check DEMO

use event.target to get clicked element .

window.onclick = function(event)
{
  if(event.target.id == "myDiv"){
    alert("here")
  }else{
    alert('Body')
  }
 console.log(event.target.id)
}  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM