Wow
Wow

Reputation: 305

Problems with contenteditable span inside hyperlink in Firefox

I've got a contenteditable span placed inside an <a> tag. I'd like to be able to edit the text inside the span so it is important to:

Both does not work in Firefox as soon as there is a href attribute in the hyperlink (which is also needed in my case). There is no problem without this attribute and there are no problems in Chrome.

Please try my example on JSFiddle.

<ul>
  <li>
    <a href="#">
      <span contenteditable="true">PlacingCursorOrTextSelectionInFirefoxImpossible</span>
    </a>
  </li>
  <li>
    <a>
      <span contenteditable="true">noProblemsHereSoFar</span>
    </a>
  </li>
</ul>

Upvotes: 2

Views: 631

Answers (2)

Tobias Buschor
Tobias Buschor

Reputation: 3305

This works for me:

  1. prevent click-default inside contenteditables
  2. and for firefox, remove and add href-attribute to prevent placing the cursor at the start of the contenteditable-element

http://jsfiddle.net/uy4q0zcm/1/

// if contenteditable inside a link
document.addEventListener('click', e=>{
    if (e.button !== 0) return;
    if (e.target.isContentEditable) {
        e.preventDefault();
    }
    if (e.explicitOriginalTarget && e.explicitOriginalTarget.isContentEditable) { // keyboard click firefox
        e.preventDefault();
    }
});

// prevent (Firefox) placing cursor incorrectly
document.addEventListener('mousedown', e=>{
    if (!e.target.isContentEditable) return;
    var link = e.target.closest('a');
    if (link) {
        const href = link.getAttribute('href')
        link.removeAttribute('href');
        setTimeout(()=>link.setAttribute('href', href))
    }
});

Upvotes: 0

YakovL
YakovL

Reputation: 8347

What you can do to improve the click behaviour is to prevent its propagation like this:

<a href="#">
  <span contenteditable="true" onclick="event.stopPropagation();">
    PlacingCursorOrTextSelectionInFirefoxImpossible
  </span>
</a>

Unfortunately, this only allows to put the cursor inside the span, but it is somewhy put to its beginning, not where one have clicked.

To enable selecting, you need to prevent the dragging behaviour, but it is to be changed for the a element:

<a href="#" draggable="false">
  <span contenteditable="true" onclick="event.stopPropagation();">
    PlacingCursorOrTextSelectionInFirefoxImpossible
  </span>
</a>

But wow, draggable="false" actually fixed the "cursor to beginning" bug! Here's the working example (tested in FF 47): https://jsfiddle.net/8v1ebkfd/4/

Upvotes: 1

Related Questions