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.
1 Answer 1
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();
-
\$\begingroup\$ You have always good ideas! Thank you! :) \$\endgroup\$Maximilian Fuchs– Maximilian Fuchs2013年12月26日 16:22:10 +00:00Commented 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\$CookieEater– CookieEater2015年07月13日 19:57:11 +00:00Commented Jul 13, 2015 at 19:57