Search code examples
javascriptdojodom-events

Programmatically firing a click handler


I'm using dojo. I've got something like this:

<a id="fooBar" onclick="foo();bar();">Foo then Bar</a>

I want to trigger fooBar's click handler from another button. Something like:

<a onclick="dojo.query('#fooBar')[0].click()">Do FooBar</a>

Can I do that?


Solution

  • dojo.byId('fooBar').onclick();
    

    or

    dojo.query('#fooBar')[0].onclick();
    

    See examples.

    I haven't used Dojo before, but can safely say that you can do better than inline events :). Moreover, these will not be managed by Dojo as they were added inline. The onclick method here is a native DOM method for triggering the function attached to the onclick property of the element.

    dojo.byId is a shortcut to document.getElementById, and honestly you can easily do without Dojo here:

    document.getElementById("fooBar").onclick();
    

    Here's the three methods with a comparison of character savings (9 and 14):

    document.getElementById('fooBar').onclick();
    dojo.query('#fooBar')[0].onclick();123456789
    dojo.byId('fooBar').onclick();12345678901234
    

    See a couple of good reasons for not using inline click handlers.