Well, i have such-like code that prevent “select all” action from keyboard:
$(document).keydown(function(e){
// CTRL key
if ( e.which == '17' || e.which == '224' ){
window.isCtrlHold = true;
}
// A key
// Prevent from select all from a page ( ctrl + a )
if ( e.which == '65' && window.isCtrlHold ){
e.preventDefault();
}
});
Another script called from another place that escape preventing off preview code:
$('input').focus(function(){
window.inSearch = true;
});
$(document).keydown(function(e){
// A ( "ctrl + a" if focus within text input )
if ( e.which == '65' && window.isCtrlHold && window.inSearch ){
// some code that do defult action eg "e.doDefault();"
}
});
In the end, i need to prevent “ctrl+a” (select all) while focus not within input[type=text] and allow to select all if focus within input.
I think you’re approaching this the wrong way, just update your first code to be like this
Notice the
&& window.inSearch.Now you can remove this block of your code
Edit: I’ve noticed more errors in your code
Note1:
isCtrlHoldshouldn’t be global, because clicking Ctrl (without holding) will make ittruefor ever (life of the page). Try to tap control (no holding) and then try to typea.Note2: you should also add something like this:
or else your script will always think that the serachbox is in focus even though it isn’t.
Note3: There’s no “opposite” of
preventDefault();, you either prevent default behavior or you don’t.