Skip to content Skip to sidebar Skip to footer

How Can I Get The Function Bound To An Onclick Attribute?

I've got a function bound to the onclick event in the html, like so: test

Solution 1:

see this document.getElementById("id_of_your_element").onclick if that help you, it will return click handler, and you can call that, but its not right to raise events manually

Solution 2:

Something like this:

Example

var defaultFunction = $('a').attr('onclick');
var defaultFunctionName = defaultFunction.substring(0, defaultFunction.indexOf('('));

$('div').on('click', function(){

   if(typeofwindow[defaultFunctionName] ==="function")
   {
         window[defaultFunctionName]();
   }
    alert('Hello universe!');
});

Solution 3:

It's just onclick attribute, no jQuery required:

<script>functionf1(){ alert('hello world'); };
</script><aonclick="f1()"id="aa">test</a><aid="bb">test2</a><script>
    bb.onclick = aa.onclick;
    // or
    bb.onclick = function (){ alert('hello bb'); };   
</script>

Solution 4:

Use this:

function f1() { 
    alert('hello world');
};
$('a').on('click', f1);

Here is your fiddle with the fix: http://jsfiddle.net/o8b5j15k/2/

Solution 5:

Instead of attempting to copy the function bound inline, you could trigger the click event programatically:

functiondefaultFunction() {
    $("a[onclick]").click(); // change selector to match your actual element
}

http://jsfiddle.net/o8b5j15k/3/

Post a Comment for "How Can I Get The Function Bound To An Onclick Attribute?"