This JavaScript code enables text editing on double-click. When you double-click certain text, it becomes editable. It uses the `contentEditable` attribute to allow editing content instantly. This functionality is helpful for creating interactive web elements that users can edit directly on the page without needing a separate input field.
This feature streamlines editing tasks without needing separate forms or pop-ups. It helps create a more intuitive user experience by allowing instant text modifications.
How to Create Contenteditable On Double Click in JavaScript
1. In your HTML file, define the text you want to make editable. Wrap it in a container, like a <div>
, and set the contenteditable
attribute to “false” initially.
<p> Double click on the following text to edit. </p> <div class="content"> <h1 tabindex="0">Welcome to CodeHim</h1> </div>
2. Use the following CSS code to style your editable content. Feel free to customize the styles according to your website’s design.
* { box-sizing: border-box; padding: 0; margin: 0; } ::selection { background-color: transparent !important; } html, body { width: 100%; height: 100%; } body{ display: flex; flex-direction: column !important; justify-content: center; align-items: center; flex-flow: column nowrap; font-family: system-ui, -apple-system, BlinkMacSystemFont; font-size: 15px; text-align: center; color: #0ff; background: teal !important; } [contenteditable="false"] { cursor: not-allowed; color: #00ffff80; opacity: 0.8; } [contenteditable]::before, [contenteditable]::after { content: ""; display: flex; justify-content: center; align-items: center; height: auto; background-color: #0ff3; width: 100px; }
3. Finally, include the following JavaScript code at the end of your HTML file or within a <script>
tag. This code ensures that the content becomes editable on the double-click event.
window.addEventListener("DOMContentLoaded",(d=>{document.body.contentEditable=!0})); const t=document.querySelector(".content");t.addEventListener("dblclick",(()=>{"false"===t.getAttribute("contenteditable")?t.setAttribute("contentEditable","true"):t.setAttribute("contentEditable","false")}));
Feel free to explore and adapt this code to suit your specific needs.
That’s all! hopefully, you have successfully created contenteditable div on double click using JavaScript. If you have any questions or suggestions, feel free to comment below.
Similar Code Snippets:
I code and create web elements for amazing people around the world. I like work with new people. New people new Experiences.
I truly enjoy what I’m doing, which makes me more passionate about web development and coding. I am always ready to do challenging tasks whether it is about creating a custom CMS from scratch or customizing an existing system.