How can I simulate an anchor click via jquery?

html, jquery, onclick, thickbox

Solution

Try to avoid inlining your jQuery calls like that. Put a script tag at the top of the page to bind to the `click` event:

<script type="text/javascript">
$(function(){
    $('#thickboxButton').click(function(){
        $('#thickboxId').click();
    });
});
</script>

<input id="thickboxButton" type="button" value="Click me">
<a id="thickboxId" href="myScript.php" class="thickbox" title="">Link</a>

Edit:

If you're trying to simulate a user physically clicking the link, then I don't believe that is possible. A workaround would be to update the button's `click` event to change the `window.location` in Javascript:

<script type="text/javascript">
$(function(){
    $('#thickboxButton').click(function(){
        window.location = $('#thickboxId').attr('href');
    });
});
</script>

Edit 2:

Now that I realize that Thickbox is a custom jQuery UI widget, I found the instructions here:

Instructions:

Create a link element (`<a href>`)

Give the link a class attribute with a value of thickbox (`class="thickbox"`)

In the `href` attribute of the link add the following anchor: `#TB_inline`

In the `href` attribute after the `#TB_inline` add the following query string on to the anchor:

?height=300&width=300&inlineId=myOnPageContent

Change the values of height, width, and inlineId in the query accordingly (inlineID is the ID value of the element that contains the content you would like to show in a ThickBox.

Optionally you may add modal=true to the query string (e.g. `#TB_inline?height=155&width=300&inlineId=hiddenModalContent&modal=true`) so that closing a ThickBox will require calling the `tb_remove()` function from within the ThickBox. See the hidden modal content example, where you must click yes or no to close the ThickBox.

Problem

I have a problem with faking an anchor click via jQuery: Why does my thickbox appear the first time I click on the input button, but not the second or third time? Here is my code: ``` <input onclick="$('#thickboxId').click();" type="button" value="Click me" /> <a id="thickboxId" href="myScript.php" class="thickbox" title="">Link</a> ``` It does always work when I click directly on the link, but not if I try to activate the thickbox via the input button. This is in FF. For Chrome it seems to work every time. Any hints?

Original source

Related problems