View Full Version : highlighting selected text using javascript

Feb 15th, 2010, 07:23 AM
HI all,

I am new to this forum and really needs your help.
Please let me know how can I highlight a selected portion of an html document with javascript such that the selected portion is repeatedly shown highlighted on each and every page refresh.

Thanks & Regards,

Philip M
Feb 15th, 2010, 08:10 AM
You would be able to do this using a cookie to record the highlighted text placed in a hidden textarea. Read the cookie <body "onload = "> and set the cookie after each selection.

This ought to move you forward (bear in mind that the textarea is hidden - you can unhide it for test purposes):-


<style = text/css">
.abc {
visibility: hidden;

<script type = "text/javascript">

var text = "";
function getActiveText(e) {
text = (document.all) ? document.selection.createRange().text : document.getSelection();
document.myform.txtarea.value = text;
return true;



Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam ipsum leo, scelerisque at dapibus ac, consectetur vel ipsum. Morbi et metus ut diam molestie ullamcorper. Suspendisse rutrum semper semper. Donec volutpat neque in lorem tempus scelerisque. Curabitur dignissim rhoncus quam ac suscipit. Donec viverra quam lobortis neque porta a sagittis urna tristique. Suspendisse nec lacus nisi. Pellentesque fermentum massa sit amet magna hendrerit vestibulum. Sed elit libero, scelerisque eu eleifend ut, interdum gravida nunc. Etiam ut nisi sapien, et tempus sem. Nam vel mi est. Mauris congue felis ut ante bibendum vehicula. Nullam nec sapien arcu, eget cursus lorem. Donec blandit, dolor tristique ornare dictum, arcu sapien vulputate dolor, et placerat risus odio ut magna. Ut magna mauris, pellentesque at ultricies vitae, fermentum vitae dolor.

<form name= "myform">
<textarea name = "txtarea" rows = "10" cols = "50" class = "abc"></textarea><br>
<input type = "button" value = "Capture Highlighted Text" onclick = "getActiveText()">
<input type = "button" value = "Clear" onclick = "document.myform.txtarea.value = ''">


However, there are cross-browser issues with highlighting text in a textarea. There are many cookie scripts to be had either in this forum or with Google.

It is not as cold as it was yesterday, but that's probably because it's a bit warmer. - Sports commentator