Boban Jovanoski

javascript handle paste event BobiYo Mar 26

1 comment Latest by nallebjörnarna

Tags: paste   javascript   rte  

How to handle the paste event in javascript. I've used this for a Rich Text Editor(RTE) paste event for a case when you don't want to paste html content but text only. Here are the steps:

First you need to bind event listener to the container (in my case body of the iframe where content is entered for the RTE.

  if (body.addEventListener){
    body.addEventListener("paste", handlepaste, false);
  } else if (el.attachEvent){
    body.attachEvent("paste", handlepaste);            
  }

The handlePasteFunction:

  function handlepaste(e) {
    var clipboardBuffer = '';

    if (e && e.clipboardData && e.clipboardData.getData) {
      if (/text\/html/.test(e.clipboardData.types)) {
        clipboardBuffer = e.clipboardData.getData('text/html');
      }
      else if (/text\/plain/.test(e.clipboardData.types)) {
        clipboardBuffer = e.clipboardData.getData('text/plain');
      }
      //using 'text/plain' is enough
    }
    else {
      clipboardBuffer = window.clipboardData.getData("Text");
      // This is how IE handles the clipoardData;
    }
    waitForPasteData(clipboardBuffer);
    if (e.preventDefault) {
      e.stopPropagation();
      e.preventDefault();
    }
    e.returnValue = false;
    return false;
  }

The waitForPasteData function actually is for making sure you have the pasted Data so it can be processed later.

      function waitForPasteData (clipboardBuffer) {
        if (clipboardBuffer != '' || body.childNodes && body.childNodes.length > 0) {
          processPaste(clipboardBuffer);
        }
        else {
          var self = {
            c: clipboardBuffer,
            timer: ''
          }
          self.timer = setTimeout(function(){
            waitForPasteData(self.c);
            clearTimeout(self.timer);
          },20);
        }
      }

      function processPaste (clipboardBuffer) {
        var postedData = sanitize(clipboardBuffer);
        if($.browser.msie === true){
          var range = iframe.contentWindow.document.selection.createRange();
          range.text = postedData;
          iframe.contentWindow.focus();
        } else {
          formatText('insertHTML', postedData);
        }
      }

In case of IE we need to use range in order to paste the data properly from the caret.

That's about it, I hope this helps somebody :)