0

I want Alt+O short keys to browse a file in my web page. "Keydown" event can handle this issue perfectly in chrome however in Firefox nothing happens unless I do a click in page. Is there any solution to my problem?

$(document).ready(function(){
 $("body").keydown(function(e){

  var keyCode = (e.which) ? e.which : window.e.keyCode;

  if(e.altKey)
    if(keyCode == 79){ //Alt+O = openFile
      e.preventDefault();
      $("#xmlFile:hidden").trigger('click')
    }
   
 });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" id="xmlFile" style="display: none;" >
sepid esf
  • 1
  • 1
  • `window.e.keyCode` doesn’t make sense. It’s `e.keyCode`. Both [`keyCode`](//developer.mozilla.org/docs/Web/API/KeyboardEvent/keyCode) and [`which`](//developer.mozilla.org/docs/Web/API/UIEvent/which) are either deprecated or non-standard. Also, what really changed from your [deleted post](/q/69305562/4642212)? Why did you repost it? – Sebastian Simon Sep 24 '21 at 09:09
  • This code works fine in Chrome browser. I realized that the previous one had problem in Chrome either, hence I repost the correct one. – sepid esf Sep 24 '21 at 09:16
  • Isn't there any solution to my problem? – sepid esf Oct 01 '21 at 04:48

1 Answers1

-1

You can not use the trigger in this way this the answer helps you to understand. jQuery trigger doesn't work on Firefox

try this:

$(document).ready(function(){
 $("body").keydown(function(e){

  var keyCode = (e.which) ? e.which : window.e.keyCode;

  if(e.altKey)
    if(keyCode == 79){ //Alt+O = openFile
      e.preventDefault();
      document.getElementById('file-input').click();
    }
   
 });
});
<input id="file-input" type="file" name="name" style="display: none;" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  • I tried above code but It works randomly. The point is that if I do click every time on the blank area of page, it works and I really don't know why ! – sepid esf Sep 24 '21 at 09:57
  • because the StackOverflow code snippet must be active, if you use this code in your the project then will solve this problem – abbas marghaei zadeh Sep 24 '21 at 10:03
  • I used your recommended code in my project.. – sepid esf Sep 24 '21 at 10:16
  • This code didn’t fix `window.e.keyCode`, it didn’t replace the deprecated properties. It only replaces `$("#xmlFile:hidden").trigger('click');` by `document.getElementById('file-input').click();` without the answer providing any understanding or explanation of how they differ and why one is better than the other. – Sebastian Simon Sep 24 '21 at 10:43