DarkGuy10
DarkGuy10

Reputation: 55

How to remove enter (linebreak) from the beginning of contenteditable span element?

I have the following code:
Type some text in place of the [Header] and press enter.
As you can see on clicking enter in the h2 element the cursor shifts to span element.
However, it adds an extra line in the beginning.
I don't know how to remove a line from the end.

function enter() {
  if (event.key == "Enter") {
    $("div#text span").focus();
  }
}
var h = $('h2').offset();
$('div#text span').click(function() {

});
div#text {
  padding: 5px;
  margin: 0;
  width: 99.3%;
  height: 99%;
  resize: none;
  font-family: 'Callibri';
  font-size: 25px;
  text-align: left;
  z-index: 99;
  line-height: 30px;
  background-color: white;
  overflow-y: scroll;
  cursor: text;
}

h2 {
  text-align: center;
  font-size: 40px !important;
}

h2:focus,
div#text span:focus {
  outline: none;
  border: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="text" spellcheck="false">
  <h2 contenteditable="true" onkeydown="enter()">[Header]</h2><span contenteditable="true">[Body]</span>
</div>

Upvotes: 0

Views: 242

Answers (1)

Anurag Awasthi
Anurag Awasthi

Reputation: 6233

Use event.preventDefault to override default behaviour on pressing enter key.

function enter() {
  if (event.key == "Enter") {
    event.preventDefault();
    $("div#text span").focus();
  }
}
var h = $('h2').offset();
$('div#text span').click(function() {

});
div#text {
  padding: 5px;
  margin: 0;
  width: 99.3%;
  height: 99%;
  resize: none;
  font-family: 'Callibri';
  font-size: 25px;
  text-align: left;
  z-index: 99;
  line-height: 30px;
  background-color: white;
  overflow-y: scroll;
  cursor: text;
}

h2 {
  text-align: center;
  font-size: 40px !important;
}

h2:focus,
div#text span:focus {
  outline: none;
  border: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="text" spellcheck="false">
  <h2 contenteditable="true" onkeydown="enter()">[Header]</h2><span contenteditable="true">[Body]</span>
</div>

Upvotes: 1

Related Questions