[javascript] how to get javaScript event source element?

Is there a way to retrieve the element source of an inline javaScript call?

I have a button like this:

<button onclick="doSomething('param')" id="id_button">action</button>

Note:

  • the button is generated from server
  • I cannot modify the generation process
  • several buttons are generated on the page, I have control only on client side.

What I have tried:

function doSomething(param){
    var source = event.target || event.srcElement;
    console.log(source);
}

On firebug I get event is not defined

Edit: After some answers, an override of the event handling using jQuery is very acceptable. My issue is how to call the original onClick function with it's original prameters, and without knowing the function name.

code:

<button onclick="doSomething('param')" id="id_button1">action1</button>
<button onclick="doAnotherSomething('param1', 'param2')" id="id_button1">action2</button>.
<button onclick="doDifferentThing()" id="id_button3">action3</button>
.
.
and so on..

So the override would be:

$(document).on('click', 'button', function(e) {
  e.preventDefault();
  var action = $(this).attr('onclick');
  /**
   * What to do here to call
   * - doSomething(this, 'param'); if button1 is clicked
   * - doAnotherSomething(this, 'param1', 'param2'); if button2 is clicked
   * - doDifferentThing(this); if button3 is clicked
   * there are many buttons with many functions..
   */
});

This question is related to javascript jquery html

The answer is


You can pass this when you call the function

<button onclick="doSomething('param',this)" id="id_button">action</button>

<script>
    function doSomething(param,me){

    var source = me
    console.log(source);
}
</script>

Try something like this:

<html>
  <body>

    <script type="text/javascript">
        function doSomething(event) {
          var source = event.target || event.srcElement;
          console.log(source);
          alert('test');
          if(window.event) {
            // IE8 and earlier
            // doSomething
           } else if(e.which) {
            // IE9/Firefox/Chrome/Opera/Safari
            // doSomething
           }
        }
     </script>

    <button onclick="doSomething('param')" id="id_button">
      action
    </button>

  </body>      
</html>

I believe the solution by @slipset was correct, but wasn't cross-browser ready.

According to Javascript.info, events (when referenced outside markup events) are cross-browser ready once you assure it's defined with this simple line: event = event || window.event.

So the complete cross-browser ready function would look like this:

function doSomething(param){
  event = event || window.event;
  var source = event.target || event.srcElement;
  console.log(source);
}

Your html should be like this:

<button onclick="doSomething" id="id_button">action</button>

And renaming your input-paramter to event like this

function doSomething(event){
    var source = event.target || event.srcElement;
    console.log(source);
}

would solve your problem.

As a side note, I'd suggest taking a look at jQuery and unobtrusive javascript


USE .live()

 $(selector).live(events, data, handler); 

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.

$(document).on(events, selector, data, handler);  

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment