Search code examples
javascriptgoogle-chromegoogle-chrome-extensiondom-events

How to get the element that fired the "onclick" event


<script>
    function clicky(e){
        console.log(e)       //the clicked element
    }
</script>
<span onClick="clicky(this)">Clickable</span>

In the script above, the console.log(e) will give me the <span> that I clicked on.
Is there any way that I could omit the clicky(this) and still get the element?
It's because I don't want to put (this) all over the document.
Any answer are welcomed.


Solution

  • See this:

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>Test</title>
      </head>
      <body>
        <div id="foo" style="background:blue; width:100px; height:100px">
        <script>
          function clicky(e){
            console.log(e); 
          }
          var foo = document.getElementById("foo");
          foo.onclick = function(e){clicky((e || window.event).target);}
        </script>
      </body>
    </html>