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.

asked Dec 25, 2013 at 21:40
\$\endgroup\$

1 Answer 1

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();
answered Dec 26, 2013 at 4:07
\$\endgroup\$
2
  • \$\begingroup\$ You have always good ideas! Thank you! :) \$\endgroup\$ Commented Dec 26, 2013 at 16:22
  • \$\begingroup\$ How did you know 60% of users are using non-IE browsers? IE has been the dominant browser in the market. \$\endgroup\$ Commented Jul 13, 2015 at 19:57

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.