Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

contenteditable not working in safari but works in chrome

I'm having a strange issue...

This works in chrome as expected but in safari it only gets .. glowing but doesn't react on key input..

this is the method that fires the text edition:

var namebloc = $(event.currentTarget).find('.column_filename');
var oldvalue = namebloc.html();

namebloc.attr('contentEditable', true).focus();
document.execCommand('selectAll',false,null);

namebloc.blur(function() 
    {
    $(this).attr('contentEditable', false).unbind( "keydown" ).unbind( "blur" );
    var newvalue = $(this).html().replace('"','&quot;').replace(/(<([^>]+)>)/ig,"");
    console.log(newvalue);
    });
namebloc.keydown(function(e)
    {
    if(e.keyCode==27){ $(this).html(oldvalue);}//escape
    if(e.keyCode==13){  $(this).blur(); }//enter    
    });

This is a screenshot in chrome when fired this works as expected... enter image description here

and this is the result in safari.. no reaction to keyboard or mouse selection: enter image description here

Any idea why and how to solve this in safari?

this is the HTML before the method is called :

<span field="filename" class="column_filename" style="width:763px;">eiffel (2).JPG</span>

This is when it's called (at the same time as screenshots)

<span field="filename" class="column_filename" style="width:763px;" contenteditable="true">eiffel (2).JPG</span>
like image 484
Vincent Duprez Avatar asked Dec 06 '13 23:12

Vincent Duprez


2 Answers

Safari has the user-select CSS setting as none by default. You can use:

[contenteditable] {
    -webkit-user-select: text;
    user-select: text;
}

To make it work.

like image 105
sean Avatar answered Nov 20 '22 20:11

sean


In Safari, despite also being WebKit based, there is differing behavior when clicking on an element that has the user-select property set. Chrome seems to key-off that css property and prevent any focus going to the element that was clicked (thanks for continuing to develop a modern and sensible browser Google), while Safari does nothing with that css property regarding focus, and sets focus on the clicked element anyway.

One solution in Safari is to use a proper html button element, but this sucks from a styling perspective.

A better solution is to trap the mousedown event (the first to fire of the Mouse type events in a click), and preventDefault() on the event. This should work in any version of Safari.

For example

<span onclick="document.execCommand('bold', false);" onmousedown="event.preventDefault();">
  <i class="material-icons">format_bold</i>
</span>
like image 2
afloesch Avatar answered Nov 20 '22 18:11

afloesch