Scott B
Scott B

Reputation: 40237

How can I simulate a click event via script?

I have a jquery accordion style menu that I'd like to add some shortcut links to across the top. When one of these shortcuts is clicked, it should have the same effect as if the user clicked the corresponding a tag that serves as that panel's header...

Here's some code...

<div>
    Application Shortcuts > <a href="" 
    onclick="simulateAclick("generalSettings")>Open General Settings</a>
</div>


<ul class="menu collapsible">
  <li class='header'><a href='#' id="generalSettings">General Settings</a>
      <ul class='acitem'>...stuff goes here...

In the example above, clicking on "Open General Settings" toggles the "acitem" UL's child elements visible. I'd just like to simulate a click on that element, from a link at the top of my app...

Upvotes: 0

Views: 760

Answers (3)

Daan
Daan

Reputation: 1879

There's an official function for this ;)

$('#generalSettings').trigger('click');

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630637

Use this:

$('#generalSettings').click();

The # prefix means to look for an element with the ID that follows.

Upvotes: 4

Jacob Relkin
Jacob Relkin

Reputation: 163318

You can use the click function on all jQuery objects to simulate a click event.

This fires the event as if it were done by the user. Except obvious event properties such as clientX and clientY, etc won't be accurate and/or available.

Upvotes: 1

Related Questions