I want this text inside <div>
to be highlighten (selected for copy) when page loads.
<div id='sample_div'>This is sample text</div>
What i tried:
$(document).ready(function(){
$('#sample_div').select();
});
I want this text inside <div>
to be highlighten (selected for copy) when page loads.
<div id='sample_div'>This is sample text</div>
What i tried:
$(document).ready(function(){
$('#sample_div').select();
});
So if I assume correctly, you want the text inside a particular div to be highlighted..
function selectText(element) {
var doc = document
, text = doc.getElementById(element)
, range, selection
;
if (doc.body.createTextRange) { //ms
range = doc.body.createTextRange();
range.moveToElementText(text);
range.select();
} else if (window.getSelection) { //all others
selection = window.getSelection();
range = doc.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
}
Working jsFiddle
The solution change based on the current browser, with older version of jQuery I use $.browser
, but now is deleted; to check it's IE and use the correct code check if document.body.createTextRange
exist like:
$(document).ready(function () {
selectText('sample_div');
});
function selectText(element) {
var text = document.getElementById(element);
if (document.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(text);
range.select();
} else {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
}