I am creating a text editor using contenteditable div. When someone presses the Enter
key it creates a new block and now I need to get focus on the new block and also I want to add a new class .is-focused
on this new block.
[NOTE]: I used javascript for the new block because It just copies the previous block by default contenteditable behavior. I don't need the previous block but need a brand new block.
let
root = document.querySelector('.root'),
old_block = document.querySelectorAll('.block'),
dummy_id = 2;
root.addEventListener('keydown', (e) => {
if (e.key !== 'Enter')
return;
e.preventDefault();
dummy_id++;
let template =
`<div id="block-${dummy_id}" class="block">Block ${dummy_id}</div>`;
root.insertAdjacentHTML('beforeend', template);
document.querySelector(`#block-${dummy_id}`).focus();
})
*,
*::before,
*::after {
box-sizing: border;
}
body {
margin: 0;
}
.root {
max-width: 700px;
margin: 1rem auto;
}
.root:focus {
outline: 0;
}
.block {
font-size: 21px;
line-height: 1.8;
color: rgba(0, 0, 0, .83)
}
.is-focused {
background-color: rgb(240, 254, 255);
}
<div class="root" contenteditable="true">
<div id="block-1" class="block">Block 1 [Paragraph]</div>
<div id="block-2" class="block">Block 2 [IMG]</div>
</div>