Asma Alfauri
Asma Alfauri

Reputation: 119

prevent contenteditable adding div on enter using pure javascript NOT jQuery

prevent contenteditable adding div on enter using pure javascript NOT jQuery

like this example http://jsfiddle.net/uff3M/

but I need it in javascript not jQuery

I solved my problem Thanks all

function enterToBr(e){
    var evt = e || window.event;
    var keyCode = evt.charCode || evt.keyCode;
    if(keyCode==13){
            document.execCommand('insertHTML', false, '<br>');
            return false;
    }
}
div{
    border:1px black solid;
    padding:10px;
}
<div contenteditable="true" id="container" onkeydown="enterToBr()">
When Enter it's create new div inside container , but I need when user press enter key create new br not new div
</div>

Upvotes: 1

Views: 1754

Answers (3)

Asma Alfauri
Asma Alfauri

Reputation: 119

function enterToBr(e){
    var evt = e || window.event;
    var keyCode = evt.charCode || evt.keyCode;
    if(keyCode==13){
            document.execCommand('insertHTML', false, '<br>');
    }
}
div{
    border:1px black solid;
    padding:10px;
display: inline-block;
}
<div contenteditable="true" id="container" onkeydown="enterToBr()">
When Enter it's create new div inside container , but I need when user press enter key create new br not new div
</div>

Upvotes: 1

Roberto Zvjerković
Roberto Zvjerković

Reputation: 10157

You can do that will CSS too.

Add display: inline-block; to your div:

div{
    display: inline-block;
}

Upvotes: 1

misorude
misorude

Reputation: 3431

Looks like all you still need to do, is properly prevent the event’s default action - return false alone does not do that in this situation.

You either need to pass this return value up the chain inside the HTML attribute used to add the handler function,

onkeydown="return enterToBr()"

or you prevent it using the appropriate method,

    if(keyCode==13){
            document.execCommand('insertHTML', false, '<br>');
            evt.preventDefault();
    }

Upvotes: 1

Related Questions