73

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?

ankit
  • 1,273
  • 3
  • 13
  • 12
  • 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 http://stackoverflow.com/questions/446892/how-to-find-event-listeners-on-a-dom-node/447106#447106 – Crescent Fresh Dec 03 '09 at 12:25
  • Still no resolution, though :) Maybe go the other way round and try to actually simulate a click by creating a MouseEvent? http://stackoverflow.com/questions/1421584/how-can-i-simulate-a-click-to-an-anchor-tag – ankit Dec 03 '09 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. – Crescent Fresh Dec 03 '09 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, https://developer.mozilla.org/En/DOM/Element.dispatchEvent – ankit Dec 03 '09 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 :) – ankit Dec 03 '09 at 13:44
  • @Ankit: Actually that answer includes the `.click()` implementation that IE supports, which wraps up everything you want to do (including navigating if no handler prevents the default action). For other browsers you actually have to bend over backwards to do what you want. – Crescent Fresh Dec 03 '09 at 14:46

7 Answers7

66

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.

Jan Hančič
  • 53,269
  • 16
  • 95
  • 99
  • See the comment to the above answer by Robert – ankit Dec 03 '09 at 11:44
  • 1
    That isn't true. It works on all events no matter how it was binded. – Jan Hančič Dec 03 '09 at 11:51
  • 2
    The click method triggers the onclick method of a link. It doesn't follow the url defined in the href attribute. – kgiannakakis Dec 03 '09 at 11:55
  • @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 Fresh Dec 03 '09 at 11:57
  • @Crescent: you are right, sorry about that. But it works if you do something like: element.onclick = ... – Jan Hančič Dec 03 '09 at 12:02
  • So, I can check for the onclick handler and any jQuery bound functions. How do I check for any events assigned using addEventListener / any other JS library ( to make it foolproof )? – ankit Dec 03 '09 at 12:09
54

Why not just the good ol' javascript?

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

weisk
  • 2,468
  • 1
  • 18
  • 18
  • 7
    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 – weisk Jan 04 '14 at 00:20
  • 1
    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 Jan 04 '14 at 07:17
  • 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. – weisk Feb 10 '14 at 13:06
  • 1
    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). – Seeven Sep 25 '14 at 20:53
  • That `[0]` does make all the difference! :) – cregox Feb 12 '15 at 11:40
  • Note: Without the jQuery library this will fail. Yes the click is on a native element, but you still are using jQuery for the query. I mean if we're being technical yes jQuery is javascript, but this will not work without the dependency of jQuery, and would not be considered "vanilla". – CTS_AE Apr 16 '18 at 22:13
39

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.

noraj
  • 3,964
  • 1
  • 30
  • 38
tanathos
  • 5,566
  • 4
  • 34
  • 46
9

Easy! Just use jQuery's click function:

$("#theElement").click();
Rob Grant
  • 7,239
  • 4
  • 41
  • 61
  • 1
    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 Dec 03 '09 at 11:43
  • @Ankit: it also triggers any inline event handler (ie `onclick="..."), but yes, otherwise you are correct. – Crescent Fresh Dec 03 '09 at 12:01
  • Ah sorry, this was a harder question than I realised! – Rob Grant Dec 03 '09 at 12:17
8

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");
Yashpal Singla
  • 1,924
  • 4
  • 21
  • 38
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.

Community
  • 1
  • 1
kgiannakakis
  • 103,016
  • 27
  • 158
  • 194
  • 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: http://stackoverflow.com/questions/446892/how-to-find-event-listeners-on-a-dom-node/447106#447106 – Crescent Fresh Dec 03 '09 at 12:05
  • 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. – ankit Dec 03 '09 at 12:18
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.

sergeych
  • 791
  • 7
  • 11