0

I looked all over for a code that will that would highlight a piece of text when I hover (or click) another text.

For instance if I have the text 'Je suis ici. I am here', when i hover the word 'here' I will have a yellow bachground for the word 'here' and for the word 'ici'. So I can show that the word here is the english corespondent for the french word 'ici'.

Something like google translator uses: http://translate.google.com/

Thanks in advance for any suggestions! Dana.

skaffman
  • 398,947
  • 96
  • 818
  • 769
Dana
  • 1
  • 1
  • 1

2 Answers2

0

The way that Google Translate does it, is to split up each word in a sentence into separate <span> tags with matching classes. These are then accessible via the DOM in JavaScript - most easily by using a framework such as JQuery.

For example, you could attach a mouseover() function to highlight the currently hovered word.

I can't give you a full example here - you'll need to come up with a starting point and develop your solution from there.

Widor
  • 13,003
  • 7
  • 42
  • 64
0

This uses the jquery library and is borrowed heavily from this answer on SO to a related question.

What it does is break up each word in a paragraph tag (<p>) and wrap it with a <span> tag with a class of highlightable and then attach an event on hover to the <span class='highlightable'> tags. If you want only one paragraph to be used, then give it an ID and bind only to those items in that given ID. If a few paragraphs, use a class or multiple IDs.

<p>Each word will be wrapped in a span.</p>
<p>A second paragraph here.</p>

<script type="text/javascript">
    $(document).ready(function() {
        // wrap words in spans
        $("p").each(function() {
            $(this).text().
                replace(/\b(\w+)\b/g, "<span class='highlightable'>$1</span>");
        });

        // bind to each highlightable span
        $('.highlightable').hover(
            function() { $(this).css('background-color','#ffff66'); },
            function() { $(this).css('background-color',''); }
        );
    });
</script>
Community
  • 1
  • 1
justkt
  • 14,610
  • 8
  • 42
  • 62
  • uf..this is way over my head :) All I get from this is this:

    bla bla word bla bla word2

    But then what..?
    – Dana Apr 15 '11 at 15:01
  • @Dana - if you already have the words in the span with class highlightable and you have the hover, then you should be able to use it as is. It's getting the words into the spans that may be an issue. You might want to read up on CSS, HTML, and Javascript to get an idea of how they work together. – justkt Apr 15 '11 at 15:48