David Lionhardt
David Lionhardt

Reputation: 85

Is there a way in JavaScript to change Enter to Shift + Enter

This is what I tried and obviously failed:

ed.on('keyup', function(e){
    console.log(e.keyCode)
    if(e.keyCode == 13 && !e.shiftKey){
        e.shiftKey = true;
        e.keyCode = 13;
        $(this).trigger(e);
    }
    else if (e.keyCode == 13 && e.shiftKey){
        e.shiftKey = false;
        e.keyCode = 13;
        $(this).trigger(e);
    }
}); 

Is there a way to do this cause based on what I seen I think I'm on the right track and most likely just not triggering it early or something similar.

Additionally, I tried using 'keypress' instead and had no luck with that.

Upvotes: 1

Views: 3599

Answers (2)

user2280102
user2280102

Reputation: 159

document.onkeydown = function onkeydown(e) {

    if (e.keyCode == 13 && e.shiftKey==false) {
        e.preventDefault(); 
        document.execCommand("insertLineBreak");    
    } 
}

Upvotes: 6

Namaskar
Namaskar

Reputation: 2119

When enter is pressed without shift, trigger keydown with enter and shift!

$('input').on('keydown', function(event) {
  if (event.keyCode == 13 && !event.shiftKey) {
    $(this).trigger(jQuery.Event("keydown", {
      keyCode: 13, // ENTER
      shiftKey: true
    }));
  } else if (event.keyCode == 13 && event.shiftKey) {
    console.log('shift + enter');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input/>

Upvotes: 4

Related Questions