jqueryhtmlonclickthickbox

How can I simulate an anchor click via jquery?


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?


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: