6

I am testing this idea of using a div on top of an invisible <input type="file" /> so I can make a fancy file uploading button. I have seen some code around but was somewhat complicated. I thought of trying this idea of using jQuery to trigger the click of the input tag from its div container

Html:

<div id="container">&nbsp;Click Me!&nbsp;
    <input type="file" id="file" />
</div>

Javascript:

$(document).ready( function() {
    $('#container').click( function() {
        $('#file')[0].click();
    })
});

Although the code runs OK on Chrome and IE, it does not run on Safari and it has a funny problem with Firefox: it triggers the click twice! Any idea why this is so? jQuery is supposed to be cross-platform and I am puzzled. Here is the fiddle

http://jsfiddle.net/kostasd/C4sCs/1/

Thanks in advance for any help!

Kostas

3
  • 3
    The work around for this is not to hide the element, but instead give it a display:block;position:absolute;top:0;left:-9999px;, then wrap it with a container that has position:relative;overflow:hidden;width:somepx;. DO NOT USE display:none. Then trigger your click; bam, cross-browsers support . Commented May 1, 2013 at 15:06
  • Thank's for the tip. I'll give it a try. Commented May 1, 2013 at 15:25
  • In the current version of Firefox it will also work with display: hidden Commented Dec 22, 2015 at 22:43

1 Answer 1

5

The different Possible Solutions which I tried are

  • Using Visiblity:hidden; width:1px; for the File input element.

The jsfiddle for it is as follow http://jsfiddle.net/C4sCs/36/

  • Using only the Css to call the file input click and not using jquery at all

    #container {
    border:1px solid #b0b0b0;
    display: inline-block;
    position:relative;
    overflow:hidden;
    cursor:pointer;
    }
    #file {  
    position:absolute;
    top:0;
    opacity:0;
    display:block;
    }
    

http://jsfiddle.net/C4sCs/42/

Sign up to request clarification or add additional context in comments.

2 Comments

Don't wrap file input in a button element! Got me. Div works though.
This was causing problems for me as well. Thanks for the hint!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.