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..
*/
});
You should change the generated HTML to not use inline javascript, and use
addEventListenerinstead.If you can not in any way change the HTML, you could get the
onclickattributes, the functions and arguments used, and “convert” it to unobtrusive javascript instead by removing theonclickhandlers, and using event listeners.We’d start by getting the values from the attributes
That gives us an array of all and any global methods called by the
onclickattribute, and the arguments passed, so we can replicate it.Then we’d just remove all the inline javascript handlers
and attach our own handlers
Inside those handlers we’d get the stored original function calls and their arguments, and call them.
As we know any function called by inline javascript are global, we can call them with
window[functionName].apply(this-value, argumentsArray), soAnd inside that click handler we can add anything we want before or after the original functions are called.
A working example