jQuery and Pasting from the clipboard

Ever needed away to detect when a user copies and pastes something into your web application? I ran into this scenario where people were coping and pasting from Microsoft Word and when I tried to export the information using PHPWord, it would corrupt. Now, most of the special MS Word characters I was able to figure out how to replace when I was running the export except bullet points. They were going to be the death of me. I came up with another solution before the export. What if I run a check to see if bullet points were pasted in a textarea??

Now, I thought this might have been taboo, but as it turns out, jQuery does have the ability to detect when this happens. However, the function happens BEFORE the text gets pasted and there’s no way to check what was in the clipboard. That is taboo. I didn’t care what exactly got pasted–I just needed to be able to tell if there is a bullet point in the textarea somewhere. To achieve this, I would set a variable that is false until the paste event is fired and then set the variable to true. After that, the keyup function would run a check for bullet points and at least one is found, replace all of them with dashes and throw a warning at the person and reset the variable to false again so it doesn’t get run when just a regular key is pressed. Here’s the code I got:

var pasted_fire = false; //Variable
$(document).on('paste', 'textarea', function (){
 pasted_fire = true; //user pasted!!
});
$(document).on('keyup', 'textarea', function (){
   if(pasted_fire){
      if($(this).val().indexOf('•') >= 0){ //Found a bullet point!
          var replace_txt = $(this).val().replace(/\•/g, "- ");
          $(this).val(replace_txt);
       }
     pasted_fire = false;
  }
});

Now, I know the whole “bullet point” check might not work in certain browsers but it does work fine in the latest Chrome and Firefox which is all I needed.

Anywho, that’s your tip of the month!

2 comments

  1. I ended up adding a timeout of 0 delay and was able to grab the html from the div where they were pasting in. If someone had a working fiddle that would help. After a given timeout scan through all the contents unwrapping tags that don’t have the class that you set earlier.

Leave a Reply

Your email address will not be published. Required fields are marked *