A good[ish] website
Web development blog, loads of UI and JavaScript topics
Any element’s content can be made editable same way form fields are, even divs, by using the contenteditable attribute.
<div id="editable-div" contenteditable>Hello!</div>
You can just edit that div 👇
Normal onChange
event, which you would listen on a normal form field, won’t work in a contenteditable
field, and event.target.value
is not a thing. But you can listen to the input
event, and the elements value can be accessed with event.target.innerText
:
const editableDiv = document.getElementById('#editable-div')
editableDiv.addEventListener('input', event => {
console.log(event.target.innerText)
})
Also, you’ve got access to Document.execCommand()
when the div is made editable.
React is winching about that:
Event though I don’t have any children in there...
As a React component, the above editable element demo would look like this:
const EditableDiv = () => {
const [divText, setDivText] = React.useState('Hello!')
return (
<>
<div
className="pink-div"
contenteditable
onInput={event => setDivText(event.target.innerText)}
>
Hello!
</div>
<div className="value-container">
<strong>Value:</strong> {divText}
</div>
</>
)
}
I’m slightly unsure where to use this... You could build a simple text editor with it, and it’s great for demos and such.
Comments would go here, but the commenting system isn’t ready yet, sorry.