jQuery Mobile calling click or tap on a hidden input[type=file] in Opera Mobile

2.3k views Asked by At

I have a form where I am uploading images, so there is obviously an input[type=file] which has a class of .image-upload,but as it looks ugly I have hidden it (display: none) and instead have a pretty button that says upload (class .upload) and on tap I want to trigger the tap/click event for the input[type=file] element so that the user can then upload an image.

The code below works on a desktop, but not on a mobile device. If I change the .click to .tap below then it works nowhere?

$(document).bind('pageshow', function() {
    $('.ui-page-active .upload').tap(function() {
        $('.ui-page-active .image-upload').click();
        return false;
    });
});

Update, I never thought that it could be a browser specific issue, but this code works in the stock Android browser, and not in Opera.

3

There are 3 answers

2
Py. On

With jQuerymobile, you're better off using virtual events like vclick. Giving something along the lines of

$(document).bind('pageshow', function() {

    $('.ui-page-active .upload').tap(function() {
        $('.ui-page-active .image-upload').trigger("vclick");
        return false;
    });
});
0
yeyene On

Try this one? DEMO http://jsfiddle.net/yeyene/5kfnT/1/

JQUERY

$(document).ready(function(){
    $(function() {
        // Bind the tapHandler callback function to the tap event on div.box
        $( ".upload" ).on( 'vclick', tapHandler ); 
        // Callback function references the event target and adds the 'tap' class to it
        function tapHandler() {
            $('.image-upload').trigger('click');
        }
    });
    
    $('.image-upload').click(function(){
        alert('Upload image!');
        // your upload image script here
    });
});  
0
tjh On

Like the OP I had this same issue, but it was with the default Android browser (4.4.2). When the file input field was hidden, I couldn't trigger a click even on it. I fixed it by keeping the input element visible, technically (i.e. omitting the display:none attribute), and just moving it off screen. For example, the HTML was something like this:

<div style="height:1px;width:1px;overflow:hidden;margin-left:-999px">
    <input id="photoInput" type="file" accept="image/*" capture>
</div>
<input id="takePhoto" type="button" value="Take photo">

And the JS was:

$('#takePhoto').tap(function() {
    $("#photoInput").trigger('click');
});

Notice that the tap event triggers a click event on the input field. I couldn't get the tap event to work with the trigger. This code is working on my Android stock browser and on the Opera mobile browser vers. 21.0.01437