0

I'm looking for a way that in a contentEditable when doing 'shift + enter' do the same as when you press just the 'enter' key what it does is put the content inside a div instead of just adding a br.

I try disabling the shift key, but no results :( hope you can help me

<div class="editableDiv" contentEditable="true"><b>Hello</b> world.</div>

div{
color: green;
}
.editableDiv{
color: salmon;
}

$('.editableDiv').on('keydown', function(event) {
if (event.keyCode == 13 && !event.shiftKey) {
    console.log('pure enter');
} else if (event.keyCode == 13 && event.altKey) {
    console.log('triggered enter');
    $(this).trigger(jQuery.Event("keydown", {
      keyCode: 13,
      altKey: false
    }));
}
});

Need trigger just press 'enter' key when press 'shift + enter'

hll33r
  • 1

2 Answers2

0

so it sounds like you want 'Shift+Enter' to do the same thing as 'Enter', correct?

If so, you might put your actions into a single, separate function, and call that in both cases. For example:

function MyFunctionName () {
  $('.editableDiv').trigger(jQuery.Event("keydown", {
    keyCode: 13,
    shiftKey: false
  }));
}

$('.editableDiv').on('keydown', function(event) {
  if (event.key === 'Enter' && !event.shiftKey) {
    console.log('pure enter');
    MyFunctionName();
  } else if (event.key === 'Enter' && event.shiftKey) {
    console.log('triggered enter');
    MyFunctionName();
  }
}

Also, if you don't need to do anything different for when the user hits 'Shift+Enter' vs 'Enter' you can shorten your code to this instead:

function MyFunctionName () {
  $('.editableDiv').trigger(jQuery.Event("keydown", {
    keyCode: 13,
    shiftKey: false
  }));
}

$('.editableDiv').on('keydown', function(event) {
   if (event.key === 'Enter') {
    MyFunctionName();
  }
}

And in that case, you may not need the code in the separate function.

I edited my answer to include the better comparison operator ===. See this for more information: Which equals operator (== vs ===) should be used in JavaScript comparisons?

Also, use key instead of keyCode, as the latter is deprecated according to https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent

KiraMiller
  • 169
  • 5
0

Assuming you have typo and altKey should be shiftKey in your question.

You can do this:

   $('.editableDiv').on('keydown', function(event) {
    var shiftEnter = event.keyCode == 13 && event.shiftKey;
    var enterOnly = event.keyCode == 13 && !event.shiftKey;
      if (shiftEnter || enterOnly) {
        console.log('triggered enter');
        //Do something here
      }
      else {
        console.log("Some other key pressed");
    });
Evik Ghazarian
  • 1,803
  • 1
  • 9
  • 24