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?

Hunsu
  • 3,281
  • 7
  • 29
  • 64
prinzdezibel
  • 11,029
  • 17
  • 55
  • 62
  • 1
    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? – Matt Apr 21 '09 at 17:37
  • 1
    @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. – KyleFarris Apr 22 '09 at 14:21
  • 3
    @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. – Senseful Apr 22 '10 at 21:25

17 Answers17

201

What worked for me was:

$('a.mylink')[0].click()
Wouter Dorgelo
  • 11,770
  • 11
  • 62
  • 80
Stevanicus
  • 7,561
  • 9
  • 49
  • 70
  • 1
    . donates that the next part is a class name. # would be for an id. – Stevanicus Dec 03 '12 at 12:27
  • 3
    If it is needed for an input, then use `focus` instead of `click` :) – Andrius Naruševičius Jan 26 '13 at 20:25
  • 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? – ChrisC Aug 20 '13 at 15:46
  • 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? – ah-shiang han Feb 12 '14 at 09:47
  • 4
    `[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. – cfeduke Mar 05 '14 at 21:10
  • You can also use `$('a.mylink').get(0).click();` - I think it's a bit nicer this way, does the same thing though. – Matt Fletcher Mar 14 '14 at 14:42
  • 8
    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. – Radley Sustaire May 19 '14 at 19:34
  • 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! – Volomike Jul 21 '16 at 08:34
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.

Community
  • 1
  • 1
John Rasch
  • 62,489
  • 19
  • 106
  • 139
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>
Jure
  • 199
  • 1
  • 2
  • 1
    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 Mar 08 '10 at 20:27
  • As eagle says, this works in webkit browsers. But note that you are not really using jQuery here (other than the $ selection) – tokland Jul 24 '10 at 15:19
  • 1
    this is missing half of the magic: http://stackoverflow.com/questions/1421584/how-can-i-simulate-a-click-to-an-anchor-tag – daniloquio Mar 02 '12 at 20:59
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) {}
damian
  • 4,024
  • 5
  • 35
  • 53
  • 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. – h0r53 Oct 11 '16 at 20:43
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

Ruwanka De Silva
  • 3,555
  • 6
  • 35
  • 51
  • 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 – iCollect.it Ltd Sep 22 '15 at 14:25
  • 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. – John Sully Dec 20 '19 at 20:26
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.

Community
  • 1
  • 1
elo80ka
  • 14,837
  • 3
  • 36
  • 43
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.

Sébastien RoccaSerra
  • 16,731
  • 8
  • 50
  • 54
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.

Christian
  • 27,509
  • 17
  • 111
  • 155
Deepak
  • 41
  • 1
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)
Sergey Glotov
  • 20,200
  • 11
  • 84
  • 98
Craig
  • 21
  • 1
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");
Yashpal Singla
  • 1,924
  • 4
  • 21
  • 38
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();
  • 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 http://example.com?#test instead of http://example.com#test. Tested on Chrome and Safari. – Senseful Apr 22 '10 at 21:21
  • In FF this will work nicely. In Webkit-browsers you will get urls as Senseful described. But this is no problem, isn't it? – sdepold Jul 19 '11 at 07:24
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.

sra
  • 23,820
  • 7
  • 55
  • 89
Julien
  • 21
  • 1
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.

waxwing
  • 18,547
  • 8
  • 66
  • 82
  • 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. – prinzdezibel Apr 21 '09 at 18:31
  • 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. – waxwing Apr 21 '09 at 18:49
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);});
fregante
  • 29,050
  • 14
  • 119
  • 159
  • 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 Mar 08 '10 at 20:29
  • I believe that document.createEventObject() should be used in IE instead, but I haven't tried it. – fregante Mar 12 '10 at 02:03
  • @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. – theazureshadow Nov 18 '11 at 23:42
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();
horse
  • 707
  • 4
  • 11
  • 30
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);
jscs
  • 63,694
  • 13
  • 151
  • 195
Singh
  • 11
  • 1
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();
wbdarby
  • 1,129
  • 12
  • 12