0

I need to create a hidden input[type=file] field and a button element. When you click the button an event is delegated to the file input so that a file dialog box opens. In modern brosers that is not a problem.

document.getElementById('readFile').onclick = function(){
            var event = document.createEvent("MouseEvent");
            event.initMouseEvent("click", false, true, window, 0, 0, 0, 80, 20, false, false, false, false, 0, null);
            filesInput.dispatchEvent(event) ;
}

or simply filesInput.click()
where filesInput is reference to the input[type=file] and #readFile is a button .

However for some reason this does not work in Firefox 3.6 and my spec require browser support Firefox>=3.6 Is there any way to fake a mouse click event in Firefox 3.6 or will I just have to show that ugly default input?

I am not using JQuery or any other framework.

Dharman
  • 30,962
  • 25
  • 85
  • 135

1 Answers1

-1

The simplest solution to what you're trying to do is this:

In this answer, I explain how to do it the easiest way:

HTML:

<label>
    <input type="file">
    My Label
</label>

CSS:

label input[type="file"] {
    position: fixed;
    top: -1000px;
}

Demo.

That's the simplest solution, and it works even in the older browsers. Please see my full answer for extra information and further explanation of why this works best.

Now, that won't work in Firefox 3.6, so for FF3.6, you could use a fallback mechanism, which would be based on these CSS tricks:

Additional CSS:

label input[type="file"], body:-moz-any-link  {
    position: static;
}
:-moz-any(html) label input[type="file"] {
    position: fixed;
}

That way, you will first change the input's position back to static for all Firefox browsers, but then for the versions that support :-moz-any() (FF4+), you change it back again to fixed. That way, you will have a functional label for your file input, with a fallback for versions 1-4.

Community
  • 1
  • 1
Joeytje50
  • 18,636
  • 15
  • 63
  • 95
  • @Dharman I've added some extra info to the answer. It's not a perfect solution, but it is much simpler for all modern browsers, and it just uses a fallback mechanism for the unsupportive FF versions. Anyway, you could also drop support for FF3.6, since [it is used less than IE6 is](http://caniuse.com/usage_table.php). Supporting outdated browsers is usually a huge hassle, and when browser usage gets below 0.5%, it's almost never worth it. – Joeytje50 May 27 '14 at 16:18
  • I don't understant that piece of CSS but the fallback works. I guess you are right, I won't worry too much about FF3.6. It is full of bugs anyway. – Dharman May 28 '14 at 08:40