Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click() works in IE but not Firefox

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.

like image 966
tgandrews Avatar asked May 11 '10 16:05

tgandrews


3 Answers

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);
} 
like image 112
tgandrews Avatar answered Nov 11 '22 11:11

tgandrews


Your code should work in Firefox. Here's a full snippet that proves it:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title></title>
<style type="text/css"><!--
--></style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript"><!--
jQuery(function($){
    $(document).ready(function(){
        $('li#first')
            .click(function(){
                alert("I've been clicked: " + $(this).text());
            })
            .click();
    });
});
//--></script>
</head>
<body>

<ul>
    <li id="first">First item</li>
    <li>Second item</li>
    <li>Third item</li>
</ul>

</body>
</html>
like image 42
Álvaro González Avatar answered Nov 11 '22 11:11

Álvaro González


try this html

<a id="link" href="url">click here</a>

js

$(document).ready(function(){
    $("#link").click(function(){
        window.location.href = $(this).attr('href');
    });
});

also if this is somethng you don't want to do theb also try something like this:

$(document).ready(function(){
        $("#link")[0].click();
    });
like image 30
Abhidev Avatar answered Nov 11 '22 11:11

Abhidev