How can I simulate an anchor click via jquery?
Asked Answered
S

17

148

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?

Semiporcelain answered 21/4, 2009 at 17:18 Comment(3)
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?Polley
@Polley 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.Divide
@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.Galleass
G
124

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.

Guinevere answered 21/4, 2009 at 17:39 Comment(6)
window.location in the click handler does not work, as then the thickbox does not work as expected.Semiporcelain
In the second example it may be advisable to use .prop() instead of attr() to get the resolved url.Prebend
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 @Pearle and comments, and on several other SO posts. The answer should be changed to that of Stevanicus.Certainty
@Schollii - feel free to edit it to your desired correctness.Guinevere
I meant that the accepted answer should be that of @stevanicusCertainty
How did this answer get 100+ upvotes??Edgell
P
201

What worked for me was:

$('a.mylink')[0].click()
Pearle answered 11/5, 2012 at 23:13 Comment(8)
. donates that the next part is a class name. # would be for an id.Pearle
If it is needed for an input, then use focus instead of click :)Involucrum
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?Hoover
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?Psychochemical
[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.Skydive
You can also use $('a.mylink').get(0).click(); - I think it's a bit nicer this way, does the same thing though.Tincal
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.Riparian
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!Cloninger
G
124

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.

Guinevere answered 21/4, 2009 at 17:39 Comment(6)
window.location in the click handler does not work, as then the thickbox does not work as expected.Semiporcelain
In the second example it may be advisable to use .prop() instead of attr() to get the resolved url.Prebend
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 @Pearle and comments, and on several other SO posts. The answer should be changed to that of Stevanicus.Certainty
@Schollii - feel free to edit it to your desired correctness.Guinevere
I meant that the accepted answer should be that of @stevanicusCertainty
How did this answer get 100+ upvotes??Edgell
C
19

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>
Cognoscenti answered 4/2, 2010 at 11:10 Comment(3)
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.Eleanoraeleanore
As eagle says, this works in webkit browsers. But note that you are not really using jQuery here (other than the $ selection)Luther
this is missing half of the magic: #1422084Iulus
R
9

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) {}
Ringler answered 7/2, 2012 at 13:11 Comment(1)
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.Pozzy
J
8

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

Julesjuley answered 8/8, 2013 at 17:16 Comment(2)
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 +1Troublous
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.Mellins
B
6

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.

Backwards answered 21/4, 2009 at 19:24 Comment(0)
A
5

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.

Austral answered 4/2, 2010 at 11:34 Comment(0)
J
4

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.

Jowers answered 1/5, 2012 at 11:34 Comment(0)
P
2

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();
Pending answered 21/4, 2009 at 17:18 Comment(2)
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.Galleass
In FF this will work nicely. In Webkit-browsers you will get urls as Senseful described. But this is no problem, isn't it?Ailment
E
2

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.

Equine answered 21/4, 2009 at 18:15 Comment(2)
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.Semiporcelain
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.Equine
P
2

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.

Priscillaprise answered 20/8, 2010 at 16:54 Comment(0)
K
2

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)
Kragh answered 12/4, 2012 at 19:52 Comment(1)
Quick and dirty, but worked for me. In jQuery this is eval($("#someid").attr("href"));Buckeye
L
2

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");
Lally answered 6/2, 2013 at 12:10 Comment(0)
G
1

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);});
Grillwork answered 8/3, 2010 at 15:24 Comment(3)
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.Eleanoraeleanore
I believe that document.createEventObject() should be used in IE instead, but I haven't tried it.Grillwork
@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.Chambertin
S
1

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);
Svensen answered 29/7, 2010 at 2:43 Comment(0)
H
1

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();
Hanuman answered 16/2, 2015 at 21:54 Comment(0)
T
0

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();
Turgent answered 20/4, 2015 at 19:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.