-2

Hello I have difficulties making the .Click() command work on all browsers, it does work on IE, but not in FF, Chrome.

SCENARIO: Unity project, scene has a button inside of it. when the button is pressed, A javascript function is called.

Inside that function I have document.getElementById("file").click();

WHAT I AM TRYING TO DO:

when the javascript function is called, i need to open a local file-browser dialogue ( <input id="file" type="file"> )

pressing a button and calling "file" works on all browsers. but trying to call a click command on type does not seems to work in FF, Chrome. Is there any alternatives? any work around? Thanks.

JUST TO CLARIFY, THERE IS NO USER INPUT ON THE WEBPAGE, the only thing i get is a javascript function that gets called inside html.

  • 1
    possible duplicate of [How to open a file / browse dialog using javascript?](http://stackoverflow.com/questions/6463439/how-to-open-a-file-browse-dialog-using-javascript) – James Thorpe Nov 21 '14 at 11:05
  • 3
    Right, `click()` is not part of the standard. Instead of simulating a click, just do what the click would have done. This may help: http://stackoverflow.com/questions/15739263/phantomjs-click-an-element/15948355#15948355. ALso https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.click. –  Nov 21 '14 at 11:05
  • You can use trigger method of jquery – Swapnil Motewar Nov 21 '14 at 11:31
  • trigger = not working in FF, CHROME. Cant get the mouse event to work for some reason. – Aleks Leškin Nov 21 '14 at 11:47

2 Answers2

0

You are correct in your observation calling .click() is not supported in Internet explorer. The usual approach to this is to make the file input element have a low opacity and position it over the button.

you can see the details of this approach here

http://www.quirksmode.org/dom/inputfile.html

Sam Greenhalgh
  • 5,952
  • 21
  • 37
0

.click is not a function in javascript to listen click event. To listen event for IE we use

.attachEvent

and for other browser we use

.addEventListener

i have made sample example, this code will work for all browser

window.onload=function()
  {
   var a=document.getElementById("abc");
    myAttachEvent(a, "click",onClickMethod ); 
  };
  function myAttachEvent(element, type, handler) {
       if (element.addEventListener) {
           element.addEventListener(type, handler, false);
       }else if (element.attachEvent) {
          element.attachEvent('on' + type, handler)
       } else {
            element['on' + type] = handler;
       }
  }
  function onClickMethod(){
   alert("clicked");
  }
div{
   background: green;
   height:100px;
   width:100px;
   
  }
<div id="abc"></div>
Swapnil Motewar
  • 1,080
  • 6
  • 12
  • But he doesn't want to **listen** for the click, he wants to **do** the click. Also, minor point, but it is not correct to say "To listen event for IE"; it should be "to listen event for *obsolete versions of* IE". –  Nov 21 '14 at 11:29