Sashi Kant
Sashi Kant

Reputation: 13465

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

Upvotes: 6

Views: 3020

Answers (8)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93551

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 (i.e. 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/

Upvotes: 3

DannyTheDev
DannyTheDev

Reputation: 4173

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');
    }
});

Upvotes: 3

Nishit Maheta
Nishit Maheta

Reputation: 6031

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)
}  

Upvotes: 0

4Dev
4Dev

Reputation: 241

Here we go.

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

Upvotes: 1

Mike Bovenlander
Mike Bovenlander

Reputation: 5416

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);
}

Upvotes: 5

Kalish
Kalish

Reputation: 833

$( "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>

Upvotes: 0

renakre
renakre

Reputation: 8291

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

Upvotes: 6

John Ayers
John Ayers

Reputation: 519

var myDiv = document.getElementById('myDiv');

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

Upvotes: 1

Related Questions