Adam McGurk
Adam McGurk

Reputation: 476

Using element on contentEditable requires two clicks for the first edit

I'm trying to edit data held in a table and choosing to use contentEditable on divs inside the <td>s, and I'm running into a really weird issue. When I go to edit it the first time, I have to click in twice, every other time after that I only have to click in once. But on the first attempt to edit I have to click in twice. Here is an example table row from my HTML:

<tr style="width:100%"> <td><div class="results" onblur="blurMe(event)" onclick="darkenBox(event)" onkeypress="enterKey(event)" >Adam McGurk</div></td><td><div class="results" onblur="blurMe(event)" onkeypress="enterKey(event)" onclick="darkenBox(event)">[email protected]</div></td><td class="delete-sales-person"><span class="delete-icon"></span></td></tr>

And here is the appropriate JS:

//Only to be used with changing data to gray on click and border on hover.
function darkenBox(e){
    const ele = e.path[0];
    ele.setAttribute("contenteditable", true);
    console.log("Editing cell data");
    ele.classList.add("darkenBox")

}

// Allows user to edit content by click
function clickEdit(e) {
    e.path[0].setAttribute("contenteditable", true);
}

//Deleted placeholder text on click
function clearText(e) {
    const ele = e.path[0];
    ele.setAttribute("contenteditable", true);
    ele.innerText='';
}

// Allows user to stop editing by pressing the, "Enter" key.
function enterKey(e){

    const keyCode = e.keyCode;
    const ele = e.path[0];
    if (keyCode === 13) {
        ele.classList.remove("darkenBox");
        ele.setAttribute("contenteditable", false);
    }

}

function blurMe(e) {
    const editedElement = e.path[0];
    editedElement.classList.remove("darkenBox");
}

Why is it requiring me to click it twice to edit the first time?

Upvotes: 3

Views: 2070

Answers (2)

CoryCoolguy
CoryCoolguy

Reputation: 1079

The first time you click it, it sets contenteditable to true. Clicking away doesn't unset that. The second time you click, contenteditable is still true. This allows you to activate the element and edit it right away. If you want to edit it on the first click, you can have all elements you intend to edit start with contenteditable enabled. Or, you can focus the element after enabling contenteditable.

ele.setAttribute("contenteditable", true);
ele.focus();

On an unrelated note, this currently doesn't work at all on firefox and I recommend that you use e.target instead of e.path[0].

Upvotes: 2

Radu Diță
Radu Diță

Reputation: 14211

Your divs start without contenteditable set. When you click on them (the first time) you set contenteditable to true, but the click is already handled so it won’t trigger an edit. Only on the next click is the browser gonna allow for edit as now contenteditable is true.

Set contenteditable to true directly in the html and should work.

Upvotes: 1

Related Questions