-1

I'm trying to implement a feature to focus "Search" field if typed anywhere in the "body". Things are kind of working fine as you see form jsfiddle demo. But in MAC Safari maching if i type "Command + C" it will focus to the search field which disable copying text. Where as in Windows "Ctrl + C" works fine.

How can we avoid "Command + C" focusing on "Search" field

http://jsfiddle.net/tomalex0/ghjo45hs/1/

tomalex
  • 1,233
  • 6
  • 17
  • 40

1 Answers1

1

Tested with Chrome on Mac, works fine. On safari, console.log("keyCode:"+e.keyCode) log 99 when key 'c' pressed: Try following code:

https://jsfiddle.net/pengyanb/s8w5do2q/1/

jQuery(document).ready(function($){

    $("body").keypress(function(e) {
       var nodeName = e.target.nodeName,
            charCode = e.which || e.keyCode,
            charStr = String.fromCharCode(charCode);
        console.log("keyCode:"+e.keyCode);
        if ((e.keyCode == 67 || e.keyCode==99) && (e.ctrlKey || e.metaKey)){
            console.log("keydown-Copy");
            return;
            
        }
       console.log(e.keyCode,"keypress");;

        if ( nodeName  == 'INPUT' || nodeName == 'TEXTAREA' ) {
            return;
        }

        if (!(/[a-z0-9]/i.test(charStr))) {
            return;
        }


        $("#search").focus();
    });
});   
<div class="searchbg">
    <div>
        Search : <input type="text" id="search" />
    </div>
 <div>
    <div>    
        Name : <input type="text" id="name" />
    </div>
    <div>
        Address :  <textarea name="address"></textarea>    
    </div>
     Try Copy Me
 </div>
    
</div>
Peter Peng
  • 1,910
  • 1
  • 27
  • 37
  • instead of `e.keyCode` we need to used `charCode` . In mozilla `e.keyCode` doesn't work http://jsfiddle.net/tomalex0/ghjo45hs/4/ – tomalex Jul 30 '15 at 03:57