Jonathan Wood Jonathan Wood - 6 months ago 61
Javascript Question

Call click handler without clicking item

I have some JavaScript/jQuery code that needs to call the checkbox's click handler after it completes.

I can use

trigger()
to call that handler; however, I see that this also causes the checkbox's checked state to toggle (as though it had been clicked).

Is there any way to call a click handler without actually performing a click on the checkbox?

Answer Source

Is there any way to call a click handler without actually performing a click on the checkbox?

Yes

The handler is just a function. Call the function:

function example() {
  $(this)...do something...
}

$(...selector...).on('click', example);

...elsewhere...

$(...another selector...).each(example)

If you don't have a reference to the function, and you want to trigger all handlers on the element without triggering the native behaviors, you can use jQuery's .triggerHandler() method.

$(...selector...).on('click', function () {...})

...elsewhere...

$(...another selector...).triggerHandler('click')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download