Search code examples
jqueryonclickcontenteditable

Button must be clicked twice to activate "contenteditable"


I'm dynamically setting the attribute of a button to contenteditable=true using a jQuery click() event.

$('.editable').on('click', function(e) {
    $(this).attr('contenteditable','true');
    //$(this).focus(); -- setting this causes blur after typing one character
});

The problem is that the button must be clicked twice in order to trigger the editing. I have tried using focus(), but this causes the blur() event to trigger after typing just one character in the button. The same click handler works fine for editing other elements (ie; DIV).

Bootply Example that demonstrates the problem.


Solution

  • It is not a 100% solution, rather a workaround, but it might have the effect you want to achieve: You could wrap the text inside the <button> tag in a span and set its class to "editable".

    <button id="editBtn" type="button">
        <span class="editable">Click to edit me</span>
    </button>
    

    Then you have to focus on click, e.g. like that:

    $(".editable").on("click", function(evt) {
        $(this).attr("contenteditable", "true")
               .focus();
    }); 
    

    See, also, this short demo.