简体   繁体   中英

file input javascript click generated not from a real mouse click chrome

i'm having trouble in chrome opening the popup for the file upload of a file input type.

As you can see here: http://jsfiddle.net/cavax/K99gg/3/ , clicking on an elements can trigger a click on the file input, but for example hovering a element wont trigger a click on the input.

$('#test').on('click', function(){
   $('#upload').trigger('click');
});
$('#test').on('mouseenter', function(){
   $('#upload').trigger('click');
});

In the real life i'm having this trouble because in a web app i'm loading throw ajax a content witch has inside an input file. At the end of the load the popup file must open, but there is no way to get this works on Chrome (workign on FF).

The problem i guess is that the action is not generated by a mouse click (hover, timeout etc) so chrome wont trigger the fileupload.

I've also tryed this: http://jsfiddle.net/cavax/K99gg/7/ , so click on the element, wait then trigger the click but nothing, because there is the "settimeout" in the middle of the click and the trigger :(

$('#test').on('click', function(){
  setTimeout(function(){
    $('#upload').trigger('click');
  }, 3000);
});

if you remove the delay: http://jsfiddle.net/cavax/K99gg/8/ it works Any idea to get this work?

If I remember correctly, mouseenter and mouseleave are specific to IE, not standard events. Maybe they were extended, but don't think they became a standard. So the event itself may generate you some problems.

To resolve this you can use a lib (like jQuery for example), that treats the browser differences (or you can check the code there and take what you need).

Second way... try mouseover... it worked better (again... didn't work with them for a while so things may have happened, but this is how I remember them to be).

There is no way to trigger click event of input file type , because of a security reason.

You may try a hack of this by setting your button/div position to absolute and top to -100px It means positioning it outside the viewport by setting above style make it works.

But for mouseenter and mouseover i don't think it's going to work!

Edit:

Moved input outside the viewport and target click event

Example on click

Side note: Right now click occurs 2 times as you have written

$('#upload').trigger('click').click();

You just need

$('#upload').trigger('click');  //  $('#upload').click() 

unless you want it to fire more than single time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM