Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
16
rated 0 times [  23] [ 7]  / answers: 1 / hits: 17958  / 12 Years ago, fri, july 6, 2012, 12:00:00

How do I go about capturing the CTRL + S event in a webpage?



I do not wish to use jQuery or any other special library.



Thanks for your help in advance.


More From » dom

 Answers
11

If you're just using native / vanilla JavaScript, this should achieve the results you are after:



var isCtrl = false;
document.onkeyup=function(e){
if(e.keyCode == 17) isCtrl=false;
}

document.onkeydown=function(e){
if(e.keyCode == 17) isCtrl=true;
if(e.keyCode == 83 && isCtrl == true) {
//run code for CTRL+S -- ie, save!
return false;
}
}


What's happening?



The onkeydown method checks to see if it is the CTRL key being pressed (key code 17).
If so, we set the isCtrl value to true to mark it as being activated and in use. We can revert this value back to false within the onkeyup function.



We then look to see if any other keys are being pressed in conjunction with the ctrl key. In this example, key code 83 is for the S key. You can add your custom processing / data manipulation / save methods within this function, and we return false to try to stop the browser from acting on the CTRL-S key presses itself.


[#84422] Thursday, July 5, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
marisela

Total Points: 103
Total Questions: 105
Total Answers: 102

Location: Solomon Islands
Member since Fri, Oct 8, 2021
3 Years ago
;