3

I want to select content text in certain tags like code by clicking on it (ready for copy-paste).

I foudn solutions when you have an ID, but my code tags don't have IDs:

<p>When I click <code>this code</code> I want it to be selected.</p>
<p>The code tags don't have IDs or tag names.</p>
<p>Here's some <code>other code</code>.</p>

This doesn't work:

$("code").click(function(){
    $(this).select();
});

It seems select() is only for inputs and textareas.

Test: http://jsfiddle.net/n6R3t/

Martin
  • 2,007
  • 6
  • 28
  • 44

3 Answers3

3

Try this jQuery plugin, shared by Jason Edelman in this answer:

jQuery.fn.selectText = function(){
    var doc = document
        , element = this[0]
        , range, selection
    ;
    if (doc.body.createTextRange) {
        range = document.body.createTextRange();
        range.moveToElementText(element);
        range.select();
    } else if (window.getSelection) {
        selection = window.getSelection();        
        range = document.createRange();
        range.selectNodeContents(element);
        selection.removeAllRanges();
        selection.addRange(range);
    }
};

You could then use it like this:

$('code').click(function() {
    $(this).selectText();
});
Community
  • 1
  • 1
Matt Browne
  • 12,169
  • 4
  • 59
  • 75
1

As you stated, the $.select() method only works for input / textareas. You'll need to use a combination of window.getSelection and document.selection (in older browsers).

$("code").click(function(){
    if (document.selection) {
        // older browsers
        var range = document.body.createTextRange();
        range.moveToElementText(this);
        range.select();
    } else if (window.getSelection) {
        // modern browsers
        var range = document.createRange();
        range.selectNode(this);
        window.getSelection().addRange(range);
    }
});

See fiddle: http://jsfiddle.net/derekaug/8Ax79/

derekaug
  • 2,145
  • 1
  • 17
  • 17
0

.select() triggers a select event. It's a shorthand for the javascript .trigger("select") http://api.jquery.com/select/, so you need to ad an event handler to your code for it to do anything, similar to the click handler you already have.

$("code").select(function(){your code for what happens on select});

Add that after your click code and it should respond.