December 08, 2015

How to Fix the .trigger('click') + File Upload Input + Android 4.2.2 Stock

If you are having a problem specifically with Android 4.2.2 stock browser not triggering click on your file upload input field, then you are not alone. This is an odd bug... Thank goodness the fix is simple.

The default styling of the file upload input field is ugly. So it’s common for us to hide it and use Javacript to manipulate the behaviour.

The common method? Hide the file input with CSS, and use .trigger('click') on another prettier element such as a div or a button to pop the file selection window.

Everything works flawlessly… and then you get a bug report specifically on the stock browser of Android 4.2.2. Why?


Solution

Apparently, if you hide the file input element with CSS, Android 4.2.2 will render it as disabled. Thus the file input will never be submitted.

To work around this, you need to unhide the file input. However, to continue to keep it out of sight, we can use a CSS hack to move the file input off the screen so that our users wouldn’t see it anyway, and the file input would work miraculously again.

<input type="file" name="uploadFile" style="height:1px;width:1px;overflow:hidden;margin-left:-999px;">

Contrary to many opinions, it has nothing to do with jQuery’s .trigger('click'). There is no need to install jQuery Mobile or resort to .trigger('vclick') etc, which may come up fairly often when googling on this issue.

Just a weird Android bug that’s all.

***

Hello! My name is Jian Jye and I work on Laravel projects as my main job. If my article was helpful to you, a shoutout on Twitter would be awesome! I'm also available for hire if you need any help with Laravel. Contact me.