Can I call jQuery's click() to follow an <a> link if I haven't bound an event handler to it with bind or click already?

Mnebuerquo picture Mnebuerquo · Nov 7, 2009 · Viewed 437.6k times · Source

I have a timer in my JavaScript which needs to emulate clicking a link to go to another page once the time elapses. To do this I'm using jQuery's click() function. I have used $().trigger() and window.location also, and I can make it work as intended with all three.

I've observed some weird behavior with click() and I'm trying to understand what happens and why.

I'm using Firefox for everything I describe in this question, but I am also interested in what other browsers will do with this.

If I have not used $('a').bind('click',fn) or $('a').click(fn) to set an event handler, then calling $('a').click() seems to do nothing at all. It does not call the browser's default handler for this event, as the browser does not load the new page.

However, if I set an event handler first, then it works as expected, even if the event handler does nothing.

$('a').click(function(){return true;}).click();

This loads the new page as if I had clicked the a myself.

So my question is twofold: Is this weird behavior because I'm doing something wrong somewhere? and why does calling click() do nothing with the default behavior if I haven't created a handler of my own?


As Hoffman determined when he tried to duplicate my results, the outcome I described above doesn't actually happen. I'm not sure what caused the events I observed yesterday, but I'm certain today that it was not what I described in the question.

So the answer is that you can't "fake" clicks in the browser and that all jQuery does is call your event handler. You can still use window.location to change page, and that works fine for me.

Answer

Peter picture Peter · Oct 9, 2012

Another option is of course to just use vanilla JavaScript:

document.getElementById("a_link").click()