skip to Main Content

I have:

  1. html grid, that might contain cell with text inputs.
  2. custom paste functionality (e.g. paste entire rows), that I want to invoke when user pastes something to the grid, but only when the event target doesn’t have default paste functionality (e.g. inputs, textareas, etc)

Consider following snippet, that show alert, when user pastes somting:

const grid = document.querySelector(".grid");

grid.addEventListener("paste", (event) => {
    alert('Grid custom paste');
});
<div class="grid" contenteditable="true">
   <div class="row" tabindex="1">
     <div class="cell" tabindex="1">Cell A</div>
     <div class="cell" tabindex="1"><input value="CellB"/></div>
   </div>
</div>

I only want to show the alert, when user pastes something to CellA, not to the input CellB.

How can I find out, that the event target has some default paste action?

2

Answers


  1. You may try the following:

    const grid = document.querySelector(".grid div.row div.cell:first-child");
    grid.addEventListener("paste", (event) => {
       alert('Grid custom paste');
    });
    
    Login or Signup to reply.
  2. const grid = document.querySelector(".grid");
    
    grid.addEventListener("paste", (event) => {
      const target = event.target;
      if (
        (target.tagName === "DIV" && target.hasAttribute("contenteditable")) ||
        (target.tagName !== "INPUT" && target.tagName !== "TEXTAREA")
      ) {
        alert('Grid custom paste');
      }
    });
    <div class="grid" contenteditable="true">
      <div class="row" tabindex="1">
        <div class="cell" tabindex="1">Cell A</div>
        <div class="cell" tabindex="1"><input value="CellB"/></div>
      </div>
    </div>

    add this condition to solve your problem

    const grid = document.querySelector(".grid");
    
    grid.addEventListener("paste", (event) => {
      const target = event.target;
      if (
        target.tagName !== "INPUT" &&
        target.tagName !== "TEXTAREA" &&
        !target.hasAttribute("contenteditable")
      ) {
        alert('Grid custom paste');
      }
    });
    <div class="grid" contenteditable="true">
      <div class="row" tabindex="1">
        <div class="cell" tabindex="1">Cell A</div>
        <div class="cell" tabindex="1"><input value="CellB"/></div>
      </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search