Jquery trigger click not working on safari browsers in mac, Ipad & Iphone

34,117

Solution 1

Found an alternative.

Just position the input type="file" over the custom button by absolute positioning it and use jQuery fadeTo('fast',0) to hide it.

Now if we click over the custom button file browser window appears.

Its working in all desktop browsers but not in iPhone & iPad as they don't allow to upload any file.

Solution 2

Instead of trigger("click") you can use the following code which works successfully in all browsers:

var evt = document.createEvent("HTMLEvents");
evt.initEvent("click", true, true); 
document.getElementById(elem_id).dispatchEvent(evt);

Solution 3

make the element visible, as trigger event doesnt work on hidden elements in mac safari.

Solution 4

The following approach did the trick for me:

$(".upload_on_click").each(function(index) {
    var form = $(this).next("form");
    //form.hide(); /* THIS TECHNIQUE DIDN'T WORK IN SAFARI */
    form.css("position", "absolute");
    form.css("visibility", "hidden");
    $(this).css("cursor", "pointer");
    $(this).click(function() {
        $('input[type="file"]', form).trigger("click");
    });
    $('input[type="file"]', form).change(function() {
        $('input[type="submit"]', form).trigger("click");
    });
});

Solution 5

.click() is not supported in Safari. Sattu's suggestion should work. But you don't need Javascript for customizing input file button.

<label><input type="file" id="file" name="file" style="position:absolute; left:-9999px;" />Upload</label>

Reference: http://noypiscripter.blogspot.com/2014/04/simplest-cross-browser-custom-upload.html

Share:
34,117
Mandeep Pasbola
Author by

Mandeep Pasbola

Creative technologist with 10+ years of experience in Developing User eXperience. Extensive experience in Health, e-commerce &amp; Insurance domain.

Updated on July 05, 2022

Comments

  • Mandeep Pasbola
    Mandeep Pasbola almost 2 years

    I am trying to trigger a click event on input type="file" on the click of an another button.

    Demo: http://jsfiddle.net/Y85g6/

    It's working fine in all browsers except on safari browsers in mac, Ipad & Iphone.

    Is there any trick to accomplish this task?

  • Zach Lysobey
    Zach Lysobey about 8 years
    that jQuery just sets the opacity to 0. CSS is probably more appropriate than using a jQuery animation
  • Alexis Wilke
    Alexis Wilke about 8 years
    Only initEvent() is now deprecated. The jQuery.trigger("click") has the advantage of using the newest available interface as made available...