Back to Blog

Get in Touch

Faking 'onpaste' in Firefox

By Michael Bleigh December 16, 2007 in javascript, browser compatibility, prototype, onpaste, firefox

Missing

When trying to find a solution for cleaning Rich Text pasting into a textarea, we needed to find a way to detect pastes and trigger an event based on said action. Internet Explorer and Safari both have an onpaste event that allows you to hook javascript into a paste event, but Firefox does not allow this.

After a little Googling, I didn’t really come across much of a solution so I decided to roll my own.

  function checkForPaste(event) {
    var e = event.element();
    if ((e.previousValue && e.value.length > e.previousValue.length + 1) ||
        (!e.previousValue && e.value.length > 1)) { 
      if (e.onpaste) {
        e.onpaste(e)
      } else if (e.readAttribute("onpaste")) {
        eval(e.readAttribute("onpaste"));
      }
    }
      e.previousValue = e.value;
  }
    
  function firefoxOnPaste() {
    $$('textarea').each(function(e) { 
      if (e.onpaste || e.readAttribute("onpaste")) {
        Event.observe(e,'input',checkForPaste);
      }
    });
  }
  
  if (Prototype.Browser.Gecko) {
    document.observe('dom:loaded', firefoxOnPaste);
  }

This snippet of code will automatically detect if an onpaste has been either added to a textarea’s attribute list (e.g. <textarea onpaste='alert("Pasted!")/>) or set programmatically. It will then automatically simulate paste detection using the oninput event and trigger the onpaste code when it believes a paste has been made.

The snippet will detect correctly for all pasting I’ve tried, including selecting a chunk and pasting a replacement. The only major caveat I’ve seen thus far is that the first input change after the page load will register as a paste if the textarea’s value has already been set. In any case, I thought it was a relatively straightforward way to solve the problem.

Medium

Michael Bleigh

Michael has been with Intridea since 2007 and works to build Intridea's portfolio of products. With many years of experience working as both a designer and a developer, Michael specializes in helping to bridge the gap between the back-end development and the front-end design of a project. Michael is a prolific member of the Ruby on Rails community, having released popular open source libraries such as OmniAuth and spoken at conferences including RailsConf and RubyConf.

More posts by Michael Bleigh

Michael Bleigh

To the troubling idea isn't about what signal you're sending to your employee...

Michael Bleigh

Node.js has a pattern that I personally enjoy: if you require a directory, it...

Michael Bleigh

Last weekend I had the opportunity to speak at RubyConf 2012 about a topic th...