Would like to programmatically select HTML within a DOM element, as if the user had selected with a mouse, precisely to avoid making them select with a mouse.
This bit of elegant code from SO post (Select all DIV text with single mouse click) works great on laptop browsers I tested (IE, Chrome, FF, Safari on Windows and Mac):
function selectText(el) {
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(el);
range.select();
console.log("select 1");
} else if (window.getSelection) {
var range = document.createRange();
range.selectNode(el);
window.getSelection().addRange(range);
console.log("select 2");
}
else {
console.log("select 3");
}
};
JSFiddle: http://jsfiddle.net/z4yMh/7/
But does not work on Safari mobile (see JSFiddle). The mobile dev console shows he console shows select 2
indicating the click event is getting called, mobile dev console shows no error (i.e. the methods selectNode()
don't seem to be null), just nothing happening.
Can't guess why. Googling is hard as select
is also used to refer to a different concept jQuery/DOM selectors.
What I'm hoping for is an effect that's like native selection in Safari mobile, as in the picture here:
This project does not use jQuery, but if that solves the problem jQuery would be fine.