i have users click link, selects html text in element (not input).
by "select" mean same way select text dragging mouse on it. has been bear research because talks "select" or "highlight" in other terms.
is possible? code far:
html:
<a href="javascript:" onclick="selecttext('xhtml-code')">select code</a> <code id="xhtml-code">some code here </code>
js:
function selecttext(element) { $("#" + element).select(); }
am missing blatantly obvious?
i have found solution this, this thread found thevillageidiot. able modify info given , mix bit of jquery create totally awesome function select text in element, regardless of browser:
function selecttext(element) { var text = document.getelementbyid(element); if ($.browser.msie) { var range = document.body.createtextrange(); range.movetoelementtext(text); range.select(); } else if ($.browser.mozilla || $.browser.opera) { var selection = window.getselection(); var range = document.createrange(); range.selectnodecontents(text); selection.removeallranges(); selection.addrange(range); } else if ($.browser.safari) { var selection = window.getselection(); selection.setbaseandextent(text, 0, text, 1); } }
edit (9/28/11):
it's been while since answer updated, , i've learned lot developer since asked , answered question. has gotten lot more attention thought would. want provide better solution original 1 posted, 1 doesn't rely on deprecated jquery methods, or jquery @ all, matter. use jquery out? sure, if can achieve same result without jquery , using feature detection instead of browser sniffing, why wouldn't you? below updated answer:
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); } } document.onclick = function(e) { if (e.target.classname === 'click') { selecttext('selectme'); } };
<div id="selectme"><p>some text goes here!</p><p>moar text!</p></div> <p class="click">click me!</p>
here updated working demo. of looking jquery plugin, made one of too (updated again).
updated (1/10/2012) per tim down's suggestion, setbaseandextent()
not needed webkit.
updated (9/19/2014) embedded code snippet
Comments
Post a Comment