6

When clicking anywhere above the "Outside" div container in the following example, the contenteditable span element gets the focus.

<div style="margin:30px">
    <span contenteditable="true" style="background:#eee">
        Hello World
    </span>
    <div>Outside</div>
</div>

Here's a jsFiddle: http://jsfiddle.net/AXM4Y/

I want the contenteditable behave more like a real text input, thus only clicking the span element itself should trigger its focus. How do I do this? How can the event capturing of the container element be stopped. I've already tried "e.stopPropagation()" with jQuery on the parent div, but it didn't work.

Simon Steinberger
  • 6,605
  • 5
  • 55
  • 97
  • Doesn't happen in Firefox or IE 11 but does in Chrome. It seems to include the top and left margins in the hit zone for the contenteditable span. Seems like a WebKit/Blink/Chrome oddity. I'd suggest avoiding putting a margin on the container, if possible. – Tim Down Jun 22 '14 at 15:36
  • I have found a solution. Have a look at my answer here: http://stackoverflow.com/a/30629511/1892693 – Hans Gustavson Jun 07 '15 at 22:44

2 Answers2

0

I fixed it with the way I put pointer-events: none on parent element and pointer-events: all on element with content editable attribute.

zigomir
  • 985
  • 2
  • 15
  • 30
0

There's quite a bit more to making a content editable behave like an input but in answer to your question, this works in Chrome 98 browser.

const myEditableContainer = document.querySelector('.my-editable__container');
const button = document.querySelector('button');
let disabled = false;
const buttonText = (disabled) => `Click to ${disabled ? 'enable' : 'disable'}`;

button.innerHTML = buttonText(disabled);
button.addEventListener('click', () => {
    disabled = !disabled;
  button.innerHTML = buttonText(disabled);
  myEditableContainer.classList.toggle('my-editable-container--disabled', disabled);
});
.my-editable__container {
  position: relative;
}
 
.my-editable__cover {
  position: absolute;
  display: block;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  pointer-events: none;
  background-color: white;
}

.my-editable-container--disabled .my-editable__cover {
  pointer-events: all;
  opacity: 0.5;
}
<div style="margin:30px">
  <div class="my-editable__container">
    <span class="my-editable" contenteditable="true" style="background:#eee">
        Hello World
    </span>
    <span class="my-editable__cover"></span>  
  </div>
    
   <button>
     Enable/Disable
   </button>
  
  <div>Outside</div>
</div>
Lee Chase
  • 1
  • 1