Home > other >  contentEditable is false only when clicked on the element
contentEditable is false only when clicked on the element

Time:12-07

I have a div and it has some elements inside it. What I want to achieve is when a user double clicks an element inside the div, it sets itself as contentEditable. For example: if a user double clicks on a p tag, it becomes editable and as soon as he clicks anywhere outside that tag, it sets contentEditable to false

But what's happening is that when I double click the p tag, it does becomes editable but when I click anywhere outside that element, it doesn't set itself to false and it only sets itself to false when I click on the same p tag again. Which is very strange. What am I doing wrong here?

Here's my code:

<html>
  <body>
    <div id="zzz">
      <h1>Welcome</h1>
      <p>this is the text</p>
      <button>click me</button>
      <u>yo</u>
    </div>
  </body>

  <script>
    let arr = [];
    let myiframe = document.getElementById("zzz");

    myiframe.addEventListener("click", function (e) {
      obj = e.target;
      arr.push(obj);
      console.log(arr);

      if (arr.length > 2) {
        arr.shift();
      }
      if (arr[0] == arr[1]) {
        console.log("same");
      } else {
        console.log("different");
        obj.contentEditable = "false";
      }
      if (event.detail === 2) {
        obj.contentEditable = "true";
        obj.focus();
      }
    });
  </script>
</html>

CodePudding user response:

e.target is the element you clicked on, so when you click on an element and modify obj.contentEditable you’re only ever modifying that element’s contentEditable property.

CodePudding user response:

If you change obj.contentEditable = "false"; to arr[0].contentEditable = "false" then upon a click it would check if the elements match and if they don't it would disable the elements property.

CodePudding user response:

I think you only need to store a single element in memory, which is the last editable element. I used .setAttribute and got it working

let arr = [];
let myiframe = document.getElementById("zzz");
let activeElement = null
myiframe.addEventListener("click", function(e) {
  obj = e.target;
  //console.log(activeElement)
  if (activeElement && activeElement !== obj) {
    activeElement.setAttribute('contenteditable', 'false');
  }
  if (event.detail === 2) {
    obj.setAttribute('contenteditable', 'true');
    activeElement = obj
    obj.focus();
  }
});
<div id="zzz">
  <h1>Welcome</h1>
  <p>this is the text</p>
  <button>click me</button>
  <u>yo</u>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related