3

How do I highlight (css: background-color) a word with JavaScript when the mouse pointer is hovering over it? It should be possible to select it by clicking on it then and saving it in a variable.

Dan
  • 31
  • 1
  • 2
  • possible duplicate of [Getting the text under the mouse pointer](http://stackoverflow.com/questions/2183335/getting-the-text-under-the-mouse-pointer) – Yi Jiang Mar 27 '11 at 11:15

1 Answers1

5
var words=$("#yourTextContainer").text().split(' ');
$("#yourTextContainer").html("");
$.each(words, function(i,val){
//wrap each word in a span tag 
$('<span/>').text(val+" ").appendTo("#yourTextContainer");

});
$("#yourTextContainer span").live("mouseover",function(){
//highlight a word when hovered 
$(this).css("background-color","yellow");
});
$("#yourTextContainer span").live("mouseout",function(){
//change bg to white if not selected 
if($(this).css("background-color") !="rgb(0, 0, 255)")
{
 $(this).css("background-color","white");
}
});
$("#yourTextContainer span").live("click",function(){
$("#yourTextContainer span").css("background-color","white");
$(this).css("background-color","blue");
//gets the text of clicked span tag
var text = $(this).text();
});

EDIT:See the example http://jsfiddle.net/aD5Mu/

Jishnu A P
  • 14,202
  • 8
  • 40
  • 50
  • This is a good answer, but keep in mind that this could be very slow with large amounts of text. – tobint Mar 27 '11 at 11:11
  • 1
    The hover styles can be done with CSS, and `delegate` will reduce the number of elements the event have to go through before hitting the handler. Otherwise, there's probably no other way to efficiently do this – Yi Jiang Mar 27 '11 at 11:17
  • amazing ... but how would I get rid of the space and points in the selection and add support for more than one paragraph? – Dan Mar 27 '11 at 12:23