To remove the contenteditable attribute when the div loses focus (on blur), you can listen for the blur event in addition to the dblclick event. Below is an updated example that includes this functionality.
Example Code with Blur Event
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Editable Div with Double Click and Blur</title>
<style>
#editableDiv {
width: 300px;
height: 100px;
border: 2px solid #ccc;
display: flex;
justify-content: center;
align-items: center;
font-size: 18px;
cursor: text;
transition: background-color 0.2s ease;
}
#editableDiv:focus {
background-color: #e0f7fa; /* Light blue background on focus */
outline: none; /* Remove outline */
}
</style>
</head>
<body>
<div id="editableDiv" contenteditable="false">Double-click to edit this text</div>
<script>
const editableDiv = document.getElementById('editableDiv');
// Event listener for double-click to make the div editable
editableDiv.addEventListener('dblclick', () => {
const isEditable = editableDiv.contentEditable === "true";
editableDiv.contentEditable = !isEditable;
// If it's now editable, focus on the div
if (!isEditable) {
editableDiv.focus();
}
});
// Event listener for blur to make the div non-editable
editableDiv.addEventListener('blur', () => {
editableDiv.contentEditable = "false"; // Remove editable attribute
});
</script>
</body>
</html>
Explanation
-
HTML Structure:
- The HTML is mostly the same, with a
div that is initially non-editable.
-
CSS:
- Styles define the appearance of the editable
div, including a light blue background on focus (when it’s editable).
-
JavaScript:
- Double Click Event: The
dblclick event toggles the contentEditable attribute. When the div is made editable, it focuses on it.
- Blur Event: The
blur event is added to listen for when the div loses focus. When this event fires, the contentEditable attribute is set to "false", making the div non-editable again.
Usage
Copy this code into an HTML file and open it in a web browser. Double-clicking on the text will make it editable, allowing you to modify it. Once you click outside of the div, it will automatically become non-editable again. This functionality provides a simple user experience for editing text within a div.