How can I simulate an anchor click via jquery?

JqueryHtmlOnclickThickbox

Jquery Problem Overview


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?

Jquery Solutions


Solution 1 - Jquery

What worked for me was:

$('a.mylink')[0].click()

Solution 2 - Jquery

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.

Solution 3 - Jquery

I've recently found how to trigger mouse click event via jQuery.

    <script type="text/javascript">
    var a = $('.path > .to > .element > a')[0];
    var e = document.createEvent('MouseEvents');
    e.initEvent( 'click', true, true );
    a.dispatchEvent(e);
    </script>

Solution 4 - Jquery

this approach works on firefox, chrome and IE. hope it helps someone:

var comp = document.getElementById('yourCompId');
try { //in firefox
    comp.click();
    return;
} catch(ex) {}
try { // in chrome
    if(document.createEvent) {
        var e = document.createEvent('MouseEvents');
        e.initEvent( 'click', true, true );
        comp.dispatchEvent(e);
        return;
    }
} catch(ex) {}
try { // in IE
    if(document.createEventObject) {
         var evObj = document.createEventObject();
         comp.fireEvent("onclick", evObj);
         return;
    }
} catch(ex) {}

Solution 5 - Jquery

Although this is very old question i found something easier to handle this task. It is jquery plugin developed by jquery UI team called simulate. you can include it after jquery and then you can do something like

<a href="http://stackoverflow.com/"></a>
$('a').simulate('click');

works fine in chrome, firefox, opera and IE10.you can download it from https://github.com/eduardolundgren/jquery-simulate/blob/master/jquery.simulate.js

Solution 6 - Jquery

The question title says "How can I simulate an anchor click in jQuery?". Well, you can use the "trigger" or "triggerHandler" methods, like so:

<script type="text/javascript" src="path/to/jquery.js"></script>
<script type="text/javascript" src="path/to/thickbox.js"></script>
<script type="text/javascript">
$(function() {
    $('#btn').click(function() {
        $('#thickboxId').triggerHandler('click');
    })
})
</script>
...
<input id="btn" type="button" value="Click me">
<a id="thickboxId" href="myScript.php" class="thickbox" title="">Link</a>

Not tested, this actual script, but I've used trigger et al before, and they worked a'ight.

UPDATE
triggerHandler doesn't actually do what the OP wants. I think 1421968 provides the best answer to this question.

Solution 7 - Jquery

I'd suggest to look at the Selenium API to see how they trigger a click on an element in a browser-compatible manner:

Look for the BrowserBot.prototype.triggerMouseEvent function.

Solution 8 - Jquery

I believe you can use:

$('#yourLink').bind('click', function() {
  //Do something over here
});

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

This will easily trigger the click function, without actually clicking on it.

Solution 9 - Jquery

Do you need to fake an anchor click? From the thickbox site:

> ThickBox can be invoked from a link element, input element (typically a button), and the area element (image maps).

If that is acceptable it should be as easy as putting the thickbox class on the input itself:

<input id="thickboxButton" type="button" class="thickbox" value="Click me">

If not, I would recommend using Firebug and placing a breakpoint in the onclick method of the anchor element to see if it's only triggered on the first click.

Edit:

Okay, I had to try it for myself and for me pretty much exactly your code worked in both Chrome and Firefox:

<html>
<head>
<link rel="stylesheet" href="thickbox.css" type="text/css" media="screen" />
</head>
<body>
<script src="jquery-latest.pack.js" type="text/javascript"></script>
<script src="thickbox.js" type="text/javascript"></script>
<input onclick="$('#thickboxId').click();" type="button" value="Click me">
<a id="thickboxId" href="myScript.php" class="thickbox" title="">Link</a>
</body>
</html>

The window pop ups no matter if I click the input or the anchor element. If the above code works for you, I suggest your error lies elsewhere and that you try to isolate the problem.

Another possibly is that we are using different versions of jquery/thickbox. I am using what I got from the thickbox page - jquery 1.3.2 and thickbox 3.1.

Solution 10 - Jquery

You can create a form via jQuery or in the HTML page code with an action that mimics your link href:

<a id="anchor_link" href="somepath.php">click here</a>.

var link = $('#anchor_link').attr('href');
$('body').append('<form id="new_form" action="'+link+'"></form>');
$('#new_form').submit();

Solution 11 - Jquery

To simulate a click on an anchor while landing on a page, I just used jQuery to animate the scrollTop property in $(document).ready. No need for a complex trigger, and that works on IE 6 and every other browser.

Solution 12 - Jquery

If you don't need to use JQuery, as I don't. I've had problems with the cross browser func of .click(). So I use:

eval(document.getElementById('someid').href)

Solution 13 - Jquery

In Javascript you can do like this

function submitRequest(buttonId) {
    if (document.getElementById(buttonId) == null
            || document.getElementById(buttonId) == undefined) {
        return;
    }
    if (document.getElementById(buttonId).dispatchEvent) {
        var e = document.createEvent("MouseEvents");
        e.initEvent("click", true, true);
        document.getElementById(buttonId).dispatchEvent(e);
    } else {
        document.getElementById(buttonId).click();
    }
}

and you can use it like

submitRequest("target-element-id");

Solution 14 - Jquery

Using Jure's script I made this, to easily "click" as many elements as you want.
I just used it Google Reader on 1600+ items and it worked perfectly (in Firefox)!

var e = document.createEvent('MouseEvents');
e.initEvent( 'click', true, true );
$(selector).each(function(){this.dispatchEvent(e);});

Solution 15 - Jquery

JQuery('#left').triggerHandler('click'); works fine in Firefox and IE7. I haven't tested it on other browsers.

If want to trigger automatic user clicks do the following:

window.setInterval(function() 
    {
        $('#left').triggerHandler('click');
    }, 1000);

Solution 16 - Jquery

This doesn't work on android native browser to click "hidden input (file) element":

$('a#swaswararedirectlink')[0].click();

But this works:

$("#input-file").show();
$("#input-file")[0].click();
$("#input-file").hide();

Solution 17 - Jquery

In trying to simulate a 'click' in unit tests with the jQuery UI spinner I could not get any of the previous answers to work. In particular, I was trying to simulate the 'spin' of selecting the down arrow. I looked at the jQuery UI spinner unit tests and they use the following method, which worked for me:

element.spinner( "widget" ).find( ".ui-spinner-up" ).mousedown().mouseup();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionprinzdezibelView Question on Stackoverflow
Solution 1 - JqueryStevanicusView Answer on Stackoverflow
Solution 2 - JqueryJohn RaschView Answer on Stackoverflow
Solution 3 - JqueryJureView Answer on Stackoverflow
Solution 4 - JquerydamianView Answer on Stackoverflow
Solution 5 - JqueryRuwanka MadhushanView Answer on Stackoverflow
Solution 6 - Jqueryelo80kaView Answer on Stackoverflow
Solution 7 - JquerySébastien RoccaSerraView Answer on Stackoverflow
Solution 8 - JqueryDeepakView Answer on Stackoverflow
Solution 9 - JquerywaxwingView Answer on Stackoverflow
Solution 10 - JqueryRus MillerView Answer on Stackoverflow
Solution 11 - JqueryJulienView Answer on Stackoverflow
Solution 12 - JqueryCraigView Answer on Stackoverflow
Solution 13 - JqueryYashpal SinglaView Answer on Stackoverflow
Solution 14 - JqueryfreganteView Answer on Stackoverflow
Solution 15 - JquerySinghView Answer on Stackoverflow
Solution 16 - JqueryhorseView Answer on Stackoverflow
Solution 17 - JquerywbdarbyView Answer on Stackoverflow