This javascript function together with some Jquery goodness selects the text inside an html element like highlighting with your mouse and works even the element is not an input type or textarea.It is cross browser compatible and is working in IE, Safari, Opera, Chrome and Firefox.This can be useful if you want to highlight some text in a paragraph tag or span tag or even in a div tab upon clicking on a part of the text so that your users would not bother dragging their mouse to select the whole text they want to copy.See the demo by clicking here.
HTML code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Selecting text in html elements with Jquery demo page</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="highlight_text.js"></script>
<style type="text/css">
body{
font-family:Verdana;
font-size:16px;
}
p{
border:1px dashed #333;
width:500px;
line-height:36px;
}
</style>
</head>
<body>
<div align="center">
<p id="highlited_text">Click on any area inside the box
to highlight all of my text.</p>
</div>
</body>
</html>
Our HTML code is pretty simple,just a div with a paragraph tag that has an id of “highlighted_text”,some css code for styling our page, and links to the jquery core and our function inside the head tags.
highlight_text.js
$(document).ready(function() {
$('#highlited_text').click(
function(){
SelectText('highlited_text');
}
);
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);
}
}
});
You can also trigger the function by clicking a button or clicking another div or an anchor tag. It depends on your preferences.By the way,Happy Valentine’s day everyone!
- Tags: highlighting text function javascript, highlighting text function Jquery, selecting text function javascript, selecting text function Jquery, selecting text inside html elements javascript, selecting text inside html elements Jquery selecting text not input javascript, selecting text not input Jquery selecting text not textarea javascript, selecting text not textarea Jquery












