3

I'm working on a terminal-like modal, using bootstrap's and I want to clear it when the user presses Ctrl+L like it does when he writes clear in it.
But the problem is, when I press Ctrl+L, it focuses the URL bar, and I don't have anymore focus on my page.
In this part, alert is showing, but it still focuses URL bar after :

if(event.key == "l" && event.ctrlKey)
    alert("clear it");

I have tried several things like focusing my terminal after a sec, or things like that. But nothing worked.
Have you got any ideas ? Thanks you !

Fabrizio
  • 7,603
  • 6
  • 44
  • 104
tektiv
  • 14,010
  • 5
  • 61
  • 70
  • 1
    try `e.preventDefault()` or `return false` from inside the if condition – Pawan May 22 '15 at 06:57
  • Check to see if this helps at all http://stackoverflow.com/questions/11000826/ctrls-preventdefault-in-chrome – Saad May 22 '15 at 06:58
  • 6
    I hate it when web applications override standard browser shortcuts like this. Flash in Chrome does it, and it's really annoying. – Barmar May 22 '15 at 06:58
  • [Have a look at this snippet](http://www.arraystudio.com/as-workshop/disable-ctrl-n-and-other-ctrl-key-combinations-in-javascript.html) – davidcondrey May 22 '15 at 07:15
  • @Barmar Well, I'm working on a terminal .. It is very boring to write `clear` to clear it. And everybody working on Unix know `Ctrl+L`, I couldn't use something else. – tektiv May 22 '15 at 07:19
  • 1
    Good point, this may be the exceptional case where it's OK. – Barmar May 22 '15 at 07:25

3 Answers3

1

Well, it wasn't hard as I thought it would be.
The only thing which worked was e.preventDefault(), I tried return false but it didn't.

if(event.key == "l" && event.ctrlKey)
{
    event.preventDefault();
    // ...
    // what I wanted to do
}

Thank you all for your quick answer and Pawan for yours in particular.

Community
  • 1
  • 1
tektiv
  • 14,010
  • 5
  • 61
  • 70
  • Sidenote: Does not to work with `keyup`. Still focusing the URL bar. But yes, works with `keydown`. – Avatar Mar 14 '22 at 06:31
0

This might help. But if you press L two times without leaving Ctrl it will not work.

sorry but I am using jQuery, but I hope you got the logic.

var key = '';
$(document).on('keydown', function(e) {
  key += e.keyCode;
  console.log(key);
  if (key === '9176' || key === '1776'){
    key = '';
    console.log('stopped');
    return false;
  }
});
$(document).on('keyup', function(e) {
  key = '';
});

an example http://jsbin.com/xicegu/3/edit

Fabrizio
  • 7,603
  • 6
  • 44
  • 104
wrick17
  • 701
  • 1
  • 5
  • 14
0

I agree with Barmar, but here you go:

document.addEventListener("keydown", function(e) {
if ((navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey) && e.keyCode === 76) {
    e.preventDefault();
    return false;
}

return true;
});

http://jsfiddle.net/L8L23u9v/

lia ant
  • 408
  • 5
  • 10