Reputation: 21
I have a <div contenteditable>
element that I want to have 8.5in by 11in page breaks like in Google Docs.
Here is some of my code:
<div id="txt" class="editor" contenteditable="true"></div>
It is not deployed yet, but the link is here.
Upvotes: 0
Views: 140
Reputation: 165
Okay check the snippet
window.addEventListener('keypress', (e) => {
// check the classname first 'myElement'
if (e.target.className === 'myElement') {
// get current element where user typing
let currentElement = e.target
const allElement = document.querySelectorAll('.myElement');
let allElementArray = [];
allElement.forEach(el => allElementArray.push(el));
const nextElementIndex = allElementArray.indexOf(currentElement) + 1
const nextElement = allElementArray[nextElementIndex];
// page height
const pageHeight = 8.5 * 96; // 1 inch = 96 px
// stop typing if a new page already created and it is crosing the height
if (currentElement.offsetHeight >= pageHeight && nextElement && e.which === 13) {
// it only prevent hitting "enter" key from keyboard.
// make it more flexible. Because not if a user don't
// hit enter key from keyboad, but keep writing, it will cross the line
// and it will increate the page or div height.
e.preventDefault()
}
if (currentElement.offsetHeight >= pageHeight && !nextElement) {
// add new page
currentElement.insertAdjacentHTML('afterend',
`<div class="myElement" contenteditable></div>`)
// focus on new page
const newElement = document.querySelectorAll('.myElement')[nextElementIndex];
newElement.focus()
}
}
})
.myElement {
background: tomato;
color: white;
min-height: 30px;
width: 500px;
margin: 0 auto 20px auto
}
.myElement:focus {
outline: 3px solid dodgerblue
}
<div class="myElement" contenteditable>Start typing here</div>
Upvotes: 1