5
\$\begingroup\$

I wrote this JS code with some jQuery and got a one-click-text-selection. Maybe someone can improve this code, because I think it's not "clean" and short engough ;) But I don't want to use an input field. Let me know if you have some ideas!

function SelectText(element) {
    var doc = document,
        text = doc.getElementById(element),
        range,
        selection;
    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);
    }
}
$(function() {
    $('p').click(function () {
        SelectText('autoselect');
    });
});

And this is the HTML part:

<div id="autoselect">
    <p>Some cool text!</p>
</div>

Here's the code in a fiddle.

\$\endgroup\$
8
\$\begingroup\$

You can further improve this by making it a jQuery plugin instead to make it reusable across any element.

non-IE browsers, combined, account for ~60% of users at the time of writing. This means 60% of the time, the two conditions are evaluated since you check for IE first. Instead, reverse the conditions to get it right on the first check 60% of the time.

$.fn.OneClickSelect = function () {
  return $(this).on('click', function () {

    // In here, "this" is the element

    var range, selection;

    if (window.getSelection) {
      selection = window.getSelection();
      range = document.createRange();
      range.selectNodeContents(this);
      selection.removeAllRanges();
      selection.addRange(range);
    } else if (document.body.createTextRange) {
      range = document.body.createTextRange();
      range.moveToElementText(this);
      range.select();
    }
  });
};

// Apply to these elements
$('p, #all-select').OneClickSelect();
\$\endgroup\$
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.