Search code examples
javascriptjqueryhtmlcsshighlighting

Highlight effect for a single line of text in a <div>


I want to recreate the effect shown in this fiddle

According to StackOverflow rules I apparently have to present some code if I link to jsfiddle.net, so here's the main function from that link. Although to see the effect you obviously have to follow the link instead.

$(document).ready(function() {
  $(".textWrapper").hover(function() {
    $(".highlight", this).show();
    $(this).mousemove(function(e) {
      var relativePos = e.pageY - this.offsetTop;
      var textRow = (Math.ceil(relativePos / 18) * 18) - 18;
      if (textRow >= 0) { $(".highlight", this).css("top", textRow + "px"); }
    });
  }, function() {
    $(".highlight", this).hide();
  });
});

Rather than highlight the text in yellow I'd prefer to change the color of the text itself.

I'd like the text to be light grey, and darken when highlighted, to bring that line into focus. This seems a lot more difficult than simply changing CSS, because the actual text properties do not change.

How do I accomplish this?


Solution

  • Take a look:

    http://jsfiddle.net/5nxr6my4/

    Using the same principle I created 2 white opaque divs #highTop and #highBot in order to overlay the text when the mouse pointer hovers over it. Their height and top properties are adjusted to the pointer position, so underlying black text appears gray, except the line at which the mouse pointer points to:

    $(document).ready(function() {
        $('#highTop').css('height', $('.textWrapper').height()).show();
    
        $('.textWrapper').hover(function() {   
            $('#highBot').show();
            $(this).mousemove(function(e) {
               var relativePos = e.pageY - this.offsetTop;
               var textRow = (Math.ceil(relativePos / 18) * 18) - 18;
               if (textRow >= 0) { 
                  // change height of #hightTop to make it cover upper part of text
                  $('#highTop').css('height', textRow + 'px'); 
                  // change position and height of #highBot to make it cover lower part of text
                  $('#highBot').css('height', $('.textWrapper').height() - 18 - textRow + "px")
                               .css('top', textRow + 18 + 'px');
               }
            });
        }, function() {
            // when the pointer goes out of the text, hide #highBot and make #highTop cover entire text
            $('#highTop').css('height', $('.textWrapper').height() + 'px');
            $('#highBot').hide();
        });
    });