select text for copy/paste

by Gerald Gillespie

HTML

<div style="border: 1px solid">
    <p id='select1'>Some text goes here!</p>
    <p>Moar text!</p>
</div>
<input type="button" id="button1" value="Select specific sub p" />
<br/>
<br/>
<div id="select2" style="border: 1px solid">
    <p>Different text!</p>
</div>
<table>
    <tr><td><code>some code</code></td></tr>
</table>

JavaScript

var SelectText = function (e) {
    console.log(e);
    var c = 'SelectText';
    $e = $(e);
    return $e.each(function () {
        var doc = document,
            $this = $(this),
            text = this,
            range, selection;
        if (!$this.hasClass('SelectText')) {
            if (doc.body.createTextRange) {
                range = document.body.createTextRange();
                range.moveToElementText(text);
                range.select();
            } else if (window.getSelection) {
                selection = window.getSelection();
                range = document.createRange();
                range.selectNodeContents(text);
                selection.removeAllRanges();
                selection.addRange(range);
            } // end if
            $this.addClass(c).children().removeClass(c);
        } else {

            if (doc.body.createTextRange) {
                range = document.body.createTextRange();
                range.moveToElementText('nothing');
                range.select();
            } else if (window.getSelection) {
                selection = window.getSelection();
                range = document.createRange();
                //  range.selectNodeContents('nothing');
                selection.removeAllRanges();
            } // end if
            $this.removeClass(c).children().removeClass(c);
        } // end if class 
    }); // end each
    console.log(doc, text, range, selection);
} // end SelectText

$('div').on('mouseenter mouseleave', function () {
    SelectText(this);
});

$('code').closest('td').on('mouseenter mouseleave', function () {
    SelectText(this);
});

$('#button1').on('click', function () {
    console.log('hi');
    SelectText($('#select1'));
}); // end on click