How can I simulate an anchor click via jquery?

289,669

Solution 1

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 2

What worked for me was:

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

Solution 3

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

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

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

Share:
289,669

Related videos on Youtube

prinzdezibel
Author by

prinzdezibel

a.k.a. mixedpickles

Updated on May 31, 2020

Comments

  • prinzdezibel
    prinzdezibel almost 4 years

    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?

    • Matt
      Matt about 15 years
      You're leaving out code here. There is no code associated with the click event for the anchor that you've shown us. What does that code do? Is there any other code involved?
    • KyleFarris
      KyleFarris about 15 years
      @Matt If you use the click method with no parameters, it is no longer interpreted as a event binding, it will actually CLICK (as if you were to click with your mouse) the element that its chained to. In this case, when the input element is clicked, the element with ID 'thickboxId' should also be clicked.
    • Senseful
      Senseful about 14 years
      @KyleFarris: The click() event doesn't work on Chrome or Safari unless the element to be clicked has an onclick event attached to it, and still will only trigger that part and not navigate to the href value. In the case above he wants it to navigate to the A tag's href property, as though the user clicked the link.
  • prinzdezibel
    prinzdezibel about 15 years
    window.location in the click handler does not work, as then the thickbox does not work as expected.
  • prinzdezibel
    prinzdezibel about 15 years
    Yes, I need to fake it and yes the click handler itself works. But in fact, I didn't set the onclick event at all and it works, but only the first time. But also with onclick handled in thickboxId it will not work.
  • waxwing
    waxwing about 15 years
    What I meant was to verify that the onclick in the anchor element is triggered every time you click the input element. Oh, and see my edit above.
  • Jeremy
    Jeremy about 14 years
    I don't think this works in IE, at least not 7 or 8, because there doesn't appear to be a createEvent method on document.
  • Jeremy
    Jeremy about 14 years
    I don't think this works in IE, at least not 7 or 8, because there doesn't appear to be a createEvent method on document.
  • fregante
    fregante about 14 years
    I believe that document.createEventObject() should be used in IE instead, but I haven't tried it.
  • Senseful
    Senseful about 14 years
    This method causes the entire page to reload rather than simply jumping to an anchor. Additionally, it also adds the "?" to the url so the page becomes example.com?#test instead of example.com#test. Tested on Chrome and Safari.
  • tokland
    tokland almost 14 years
    As eagle says, this works in webkit browsers. But note that you are not really using jQuery here (other than the $ selection)
  • sdepold
    sdepold almost 13 years
    In FF this will work nicely. In Webkit-browsers you will get urls as Senseful described. But this is no problem, isn't it?
  • xusame
    xusame over 12 years
    @bfred.it: It seems createEventObject in IE is more for creating an event object to pass to handlers, rather than dispatching a synthetic event. IE's fireEvent may be closer to dispatchEvent, but it'll only trigger listeners -- not default browser actions. However, in IE you can just call the click method.
  • daniloquio
    daniloquio about 12 years
    this is missing half of the magic: stackoverflow.com/questions/1421584/…
  • mhenry1384
    mhenry1384 about 12 years
    Quick and dirty, but worked for me. In jQuery this is eval($("#someid").attr("href"));
  • Stevanicus
    Stevanicus over 11 years
    . donates that the next part is a class name. # would be for an id.
  • Andrius Naruševičius
    Andrius Naruševičius over 11 years
    If it is needed for an input, then use focus instead of click :)
  • ChrisC
    ChrisC over 10 years
    This works for me as well, but why does this work? Why does $('a.mylink')[0].click() work but $('a.mylink').eq(0).click() does not?
  • Kevin Bowersox
    Kevin Bowersox over 10 years
    In the second example it may be advisable to use .prop() instead of attr() to get the resolved url.
  • ah-shiang han
    ah-shiang han about 10 years
    damn! why is the [0] necessary? weird that click() doesn't get trigger the other selector, what does "[0] gets the first (DOM) element" do?
  • cfeduke
    cfeduke about 10 years
    [0] indicates the first element of the array - a selector returns 0 or more elements when its executed. Its unfortunate that .click() doesn't seem to work directly here since seemingly other invocations are applied to collections of elements from selectors consistently across the framework.
  • Matt Fletcher
    Matt Fletcher about 10 years
    You can also use $('a.mylink').get(0).click(); - I think it's a bit nicer this way, does the same thing though.
  • Radley Sustaire
    Radley Sustaire almost 10 years
    Using [0] or .get(0) are the same. These use the DOM version of the element, instead of the jQuery version. The .click() function in this case is not the jQuery click event, but the native one.
  • Oliver
    Oliver almost 10 years
    I'm surprised this is the accepted answer. The click trigger will only work on the native DOM element, not on the jQuery wrapper element. This is discussed by @Stevanicus and comments, and on several other SO posts. The answer should be changed to that of Stevanicus.
  • Summer Sun
    Summer Sun almost 10 years
    @Schollii - feel free to edit it to your desired correctness.
  • Oliver
    Oliver almost 10 years
    I meant that the accepted answer should be that of @stevanicus
  • Gone Coding
    Gone Coding over 8 years
    A key feature of simulate() is that it sends the jQuery events as well as triggering the native browser action. This is now the correct answer +1
  • Volomike
    Volomike almost 8 years
    If doing a forced file download, this technique worked for me with Chrome and Firefox only if I made the link have target="_blank". I haven't tested in Opera, IE, Edge, or Safari yet, however. EDIT: Ah, but Chrome throws open a popup blocker if it occurs too many times!
  • h0r53
    h0r53 over 7 years
    Very helpful and the better option due to cross compatibility in my opinion. I don't like having to wrap everything in try/catch blocks but I understand this is done to cascade attempts for each browser.
  • John Sully
    John Sully over 4 years
    Works like a charm and it lets me open the page in a new tab when the user clicks on a button in my kendo grid.
  • Jeremy Moritz
    Jeremy Moritz over 2 years
    How did this answer get 100+ upvotes??