28
Aug '13

jQuery Copy to Clipboard Function (IE Only)

You won’t often find me posting an IE only chunk of code here but today I’m making an exception as I have found myself writing a site specifically for use in a call-centre where I know for a fact that everyone will be using IE so I can make a few custom nice-to-haves with that in mind.

IE, for all its faults, is the only browser that will let you implement a copy to clipboard function without the need for Flash plugins. There are lots of tutorials out there that show you ways to do this, but I ended up building a very quick jQuery function that I thought I’d share.

This assumes that you have a container with a class of ‘copy_text’ and a button, link or other clickable element with the class of ‘copy_to_clipboard’:

$('.copy_to_clipboard').click(function(e) {
    e.preventDefault();

    if (!document.all)
        return; // IE only

    var copy_text = $(this).siblings('.copy_text').html();
    var new_element = document.createElement('input');
    new_element.setAttribute('type', 'text');
    new_element.setAttribute('class', 'copy_text_dynamic');
    new_element.setAttribute('value', copy_text);
    document.body.insertBefore(new_element)

    r = new_element.createTextRange();
    r.execCommand('copy');
});

Now you’ll notice this has created an input element on the fly. This is because IE’s createTextRange call only works on input elements so we have to create one and fill it with the text that we want to copy to the clipboard.

The final part of this process is making sure that this newly created input element doesn’t show up on our page. You may have already noticed that you can’t hide an element (i.e. display: none) in IE if you want to do anything with it as it doesn’t bother putting hidden elements in the DOM. That being the case, as an alternative I prefer to fix the position of the element and send it way off the side of the screen like so:

.copy_text_dynamic {
    display: block;
    position: fixed;
    left: -10000px;
}

Leave a Reply