149

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?

3
  • 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? Commented Apr 21, 2009 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. Commented Apr 22, 2009 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. Commented Apr 22, 2010 at 21:25

17 Answers 17

203

What worked for me was:

$('a.mylink')[0].click()
Sign up to request clarification or add additional context in comments.

8 Comments

. donates that the next part is a class name. # would be for an id.
If it is needed for an input, then use focus instead of click :)
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?
[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.
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.
|
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.

6 Comments

window.location in the click handler does not work, as then the thickbox does not work as expected.
In the second example it may be advisable to use .prop() instead of attr() to get the resolved url.
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.
@Schollii - feel free to edit it to your desired correctness.
I meant that the accepted answer should be that of @stevanicus
|
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>

3 Comments

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.
As eagle says, this works in webkit browsers. But note that you are not really using jQuery here (other than the $ selection)
this is missing half of the magic: stackoverflow.com/questions/1421584/…
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) {}

1 Comment

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.
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

2 Comments

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
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.
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.

Comments

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.

Comments

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.

Comments

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.

2 Comments

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.
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.
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();

2 Comments

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.
In FF this will work nicely. In Webkit-browsers you will get urls as Senseful described. But this is no problem, isn't it?
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.

Comments

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)

1 Comment

Quick and dirty, but worked for me. In jQuery this is eval($("#someid").attr("href"));
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");

Comments

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);});

3 Comments

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.
I believe that document.createEventObject() should be used in IE instead, but I haven't tried it.
@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.
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);

Comments

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();

Comments

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.