0

The following code is throwing two alerts as expected in IE but not in Firefox. Please help.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  
<SCRIPT LANGUAGE="JavaScript">
<!--
    function myFunction(){
        alert('myfunc');
        document.getElementById('mylabel').click();
    }
//-->
</SCRIPT>

 </HEAD>

 <BODY>
  <p id='mylabel' onclick="alert('you reached');"></p>


  <input type='button' value="Click me" onclick='myFunction();'/>
 </BODY>
</HTML>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
bragboy
  • 34,892
  • 30
  • 114
  • 171

3 Answers3

4

Firefox only has a click() function for form elements such as buttons. However, you can call the onClick function directly; you can change the line to

document.getElementById('mylabel').onclick();

This works in firefox or IE (but note that it requires that the function actually exists, which you know it does in this example).

Also note that you aren't actually simulating a click on that element (so, for example, if there were other things that such a click would do, such as also act as a click on the container, they won't happen). You're just getting the function that would run on a click, and running it directly. So it's not a solution for all situations where you need to simulate a click.

Jacob Mattison
  • 50,258
  • 9
  • 107
  • 126
3

There's no click method on elements. Are you using any library?

Usually you have to do something like element.fireEvent('click') (prototype, mootools)

or element.click() (jquery)

UPDATE- Similar question: How do I programmatically click on an element in JavaScript?

Looks like an ugly and brittle solution, if I were you I'd just include jQuery and let that handle all the browser quirks.

Community
  • 1
  • 1
adamJLev
  • 13,713
  • 11
  • 60
  • 65
  • IE supports a lot of things that are not part of the standard Javascript implementation, but they won't work in other browsers. – adamJLev Mar 18 '10 at 15:33
  • ok.. but wat will be the work around ? is there a way i could do this without using any libraries like jQuery ? – bragboy Mar 18 '10 at 15:34
  • It looks like Firefox does support `click` on certain elements, but it's still not part of the standard and therefore a bad practice. https://developer.mozilla.org/en/DOM/element.click – adamJLev Mar 18 '10 at 15:35
0

Because the <p> tag does not have the method click.

mhitza
  • 5,709
  • 2
  • 29
  • 52