div duplicate on enter

Viewed 140

I have a div inside my editable container and when I press enter the div duplicate and I end up have two divs one on the top of the other. the container have contenteditable as true, this might be causing this issue. but is there anyway i can prevent this

<div class="singlediv"></div>

with the css

.singlediv {
    border-color: rgb(155, 196, 243);
    border: dotted 1px;
    width: 100%;
    padding: 10px;
    min-height: 75px;
}

code here

2 Answers

You can have a function like following in your js :-

const handleEnter=(e)=>{
if(e.keyCode===13)
{
e.preventDefault();
}
}

And your html will be-

  <div contenteditable="true" onkeypress="handleEnter(event)">
        <div class="singlediv"></div>
    </div>

The function handleEnter ensures to prevent the the default behaviour when pressing enter button on a div with .contentEditable attribute. The key code for Enter key is 13.

This is more of a hack. If you can prevent having the inner div, then do so.

That's really simple, if you make contenteditable with a div withing then you press enter an another div will be created. This code run corretly :

 .singlediv {
            border-color: rgb(155, 196, 243);
            border: dotted 1px;
            width: 100%;
            padding: 10px;
            min-height: 75px;
        }
<div contenteditable="true" class="singlediv"></div>

Related