[jquery] How can I simulate an anchor click via jquery?

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?

This question is related to jquery html onclick thickbox

The answer is


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.


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

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

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.


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.


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

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

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

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

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>

What worked for me was:

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

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


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.


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.


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

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)

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to onclick

How to use onClick with divs in React.js React prevent event bubbling in nested components on click React onClick function fires on render Run php function on button click Passing string parameter in JavaScript function Simple if else onclick then do? How to call a php script/function on a html button click Change Button color onClick RecyclerView onClick javascript get x and y coordinates on mouse click

Examples related to thickbox

How can I simulate an anchor click via jquery? jQuery .ready in a dynamically inserted iframe