views:

183

answers:

2

I have code which is trivial but only works in IE not Firefox.

$(document).ready(function(){
    $('li#first').click();
});

I have also tried:

document.getElementById('first').click();

But that doesn't work either.

Is this an IE bug/feature or is click() not supported in the other browsers?

Responding to comments:

  1. There is a single element with ID first, no more.
  2. It is an onclick on the list element that expands the element and moves focus on a Google Map element.
  3. Running the code in patrick's response (adding another click event to the element) produced some interesting behaviour. When running $('li#first').click() only the new event fired, but physically clicking the element with the mouse fired both (new and original).

Thanks in advance.

A: 

Hi Tom,

Are you trying to go to the first link? You can't trigger a link's default action via a click.

But here's a workaround:

var link = jQuery("#first>a", this)
if(!link.onclick) window.open(link.href, link.target || "_self")
else jQuery(link).click()

Source: http://forum.jquery.com/topic/jquery-a-0-click-not-working

XaviEsteve
It is an onclick on the list element that expands the element and moves focus on a Google Map element.
tgandrews
A: 

Firefox does not support click().

Running document.getElementById('first').click() returns the following error click is not a function

So I added a snippet of code to add click() functionality to every element. This code was found after a painful series of google searches resulting in this thread.

The snippet is below and needs to be included just once on the page:

HTMLElement.prototype.click = function() {
   var evt = this.ownerDocument.createEvent('MouseEvents');
   evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
   this.dispatchEvent(evt);
} 
tgandrews
jQuery's version of `click()` should have worked in Firefox. So this answer solves the problem you were having?
patrick dw
@patrick: Yeah it does. jQuery `click()` only worked when the event was added with jQuery.
tgandrews
Strange. I can fire a handler set up by an inline "onClick" in Firefox if I use jQuery's `.click()` function (jQuery 1.4.2). Glad you got it working, though.
patrick dw
I will edit the question to include the original code tomorrow.
tgandrews