75

I want to simulate a click on any link on a page using JavaScript. If that link has some function binded to its 'onclick' event (by any other JS I don't have any control over), then that function must be called otherwise the link should behave in the normal manner and open a new page.

I am not sure that just checking the value of the 'onclick' handler would suffice. I want to build this so that it works on any link element.

I have no control over what function maybe binded to the onclick event of the link using whichever JS library (not necessarily jQuery) or by simply using JavaScript.

EDIT: With the help of the answers below, it looks like it is possible to check for event handlers attached using jQuery or using the onclick attribute. How do I check for event handlers attached using addEventListener / any other JS library so that it is foolproof?

6
  • 1
    "How do I check for event handlers attached using addEventListener / any other JS library so that it is foolproof"? Now that is a duplicate ;) See stackoverflow.com/questions/446892/… Commented Dec 3, 2009 at 12:25
  • Still no resolution, though :) Maybe go the other way round and try to actually simulate a click by creating a MouseEvent? stackoverflow.com/questions/1421584/… Commented Dec 3, 2009 at 12:37
  • @Ankit: yes exactly, that 2nd answer will fire handlers no matter how they were attached. You still say "otherwise the link should behave in the normal manner and open a new page". You're going to have problems with that. Sorry I don't have time to be more helpful here. Commented Dec 3, 2009 at 13:23
  • @Crescent I tried the above method and it works (that method is only for Firefox) the dispatchEvent() method returns a bool value depending upon if preventDefault() was fired or not. I check that value and if the links's href attribute is set to see if the link should open another page, developer.mozilla.org/En/DOM/Element.dispatchEvent Commented Dec 3, 2009 at 13:41
  • @Crescent Btw, you've been quite helpful. It think I'm going to use StackOverflow a lot more instead of endless googling :) Commented Dec 3, 2009 at 13:44

7 Answers 7

67

You can use the the click function to trigger the click event on the selected element.

Example:

$( 'selector for your link' ).click ();

You can learn about various selectors in jQuery's documentation.

EDIT: like the commenters below have said; this only works on events attached with jQuery, inline or in the style of "element.onclick". It does not work with addEventListener, and it will not follow the link if no event handlers are defined. You could solve this with something like this:

var linkEl = $( 'link selector' );
if ( linkEl.attr ( 'onclick' ) === undefined ) {
    document.location = linkEl.attr ( 'href' );
} else {
    linkEl.click ();
}

Don't know about addEventListener though.

Sign up to request clarification or add additional context in comments.

6 Comments

See the comment to the above answer by Robert
That isn't true. It works on all events no matter how it was binded.
The click method triggers the onclick method of a link. It doesn't follow the url defined in the href attribute.
@Jan: That isn't true either. It works on the inline onclick handler, but otherwise only events bound with jQuery itself. If there were other events bound with addEventListener for example jQuery would miss those.
@Crescent: you are right, sorry about that. But it works if you do something like: element.onclick = ...
|
55

Why not just the good ol' javascript?

$('#element')[0].click()

6 Comments

By accessing the first element in the jQuery set, you're obtaining a DOM element, and next you're calling a method from the HTMLElement interface, which is in fact, the good ol' javascript
Ah! my bad. I didn't pay attention to the [0]. But why do this? jQuery supports a .click() method as well, so simply $('#element').click() should suffice. If, on the other hand, you really really want to do it in plain ol' javascript, document.getElementById('element').click() would do, right?
SNag, I remember having to do that once because in IE the jQuery .click or .trigger functions weren't actually triggering the event... So, you'd be geting advantage over the powerful jquery selectors and then just obtaining the DOM element to do any javascript to it.
Thanks alot my friend, the good ol' javascript worked where the brand new javascript failed :D (if you wonder in which situation : trying to trigger a click on a Facebook's "Poke" button with JavaScript).
That [0] does make all the difference! :)
|
43

trigger("click") replaces .click() which is deprecated since jQuery 3.3.

$("#your_item").trigger("click");

using .trigger() you can simulate many type of events, just passing it as the parameter.

Comments

9

Easy! Just use jQuery's click function:

$("#theElement").click();

3 Comments

From what I've read, doesn't jQuery's click() function only trigger those functions that have been bounded to the element's click event using jQuery? It doesn't work anyways.
@Ankit: it also triggers any inline event handler (ie `onclick="..."), but yes, otherwise you are correct.
Ah sorry, this was a harder question than I realised!
9

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

2 Comments

This is working great. Thanks for posting the non-jquery version.
For some reason, jquery click() didn't work, but dispatchEvent worked. Any idea why ? I was clicking on the ExtJS website through a chrome extension
1

At first see this question to see how you can find if a link has a jQuery handler assigned to it.

Next use:

$("a").attr("onclick")

to see if there is a javascript event assigned to it.

If any of the above is true, then call the click method. If not, get the link:

$("a").attr("href")

and follow it.

I am afraid I don't know what to do if addEventListener is used to add an event handler. If you are in charge of the full page source, use only jQuery event handlers.

2 Comments

True, but events bound with "other JS I don't have any control over" (as the OP mentions) such as addEventListener or attachEvent jQuery has no way to know about those: stackoverflow.com/questions/446892/…
It would have been so much easier if I was in charge of the page source. Unfortunately, I'm building this as a plugin and so it needs to be completely foolproof.
0

All this might not help say when you use rails remote form button to simulate click to. I tried to port nice event simulation from prototype here: my snippets. Just did it and it works for me.

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.