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(typeof window[defaultFunctionName] ==="function")
   {
         window[defaultFunctionName]();
   }
    alert('Hello universe!');
});

Solution 3:

It's just onclick attribute, no jQuery required:

<script>
    function f1(){ alert('hello world'); };
</script>

<a onclick="f1()" id="aa">test</a>
<a id="bb">test2</a>

<script>
    bb.onclick = aa.onclick;
    // or
    bb.onclick = function (){ alert('hello bb'); };   
</script>

Solution 4:


Solution 5:

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

function defaultFunction() {
    $("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?"