-1

i searched everywhere for this problem but i still cant get a good example, i want to select a word from lets say a paragraph and highlight it as i click on it , i know you can highlight the whole paragraph but thats not what im looking for, please if anyone knows or have an idea of how this is done please do let me know .

Thank You.

Walid
  • 73
  • 1
  • 1
  • 9

3 Answers3

2

You can try to split the sentence into words and add the words in a span tag. Then on click on the span tag to add a class highlight :)

var sentence = $('.sentence').html().split(/\s+/),    
    result = []; 

for( var i = 0; i < sentence.length; i++ ) {
    result[i] = '<span>' + sentence[i] + '</span>';
}

$('.sentence').html(result.join(' '));

$('.sentence').on('click', 'span', function(){
    $(this).addClass('highlight');
});
.sentence span:hover, .highlight{
    background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<p class="sentence">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Similique aliquam totam odit excepturi reiciendis quam doloremque ab eius quos maxime est deleniti praesentium. Quia porro commodi blanditiis iure dicta voluptatibus.</p>
Bojan Petkovski
  • 6,835
  • 1
  • 25
  • 34
1

You could preprocess your text by surrounding every word with a <span> and set a listener on the paragraph to find <span> targets, then highlight the element however you want

chazsolo
  • 7,873
  • 1
  • 20
  • 44
1

I did a quick google search (as I figured somebody has probably already covered this) and this jsfiddle I modified slightly from https://stackoverflow.com/a/20567136/1856947 pretty much does what you need (not saying it's the best way):

$('div').each(function() {
    var $this = $(this);
    $this.html($this.text().replace(/\b(\w+)\b/g, "<span>$1</span>"));
});

$('div span').click(
    function() { 
        $(this).css('background-color','#ffff66');
    }
);

http://jsfiddle.net/z7nkU/7/

Community
  • 1
  • 1
robhuzzey
  • 36
  • 4
  • Thank you sir this example looks perfect i modified it a bit to make it exactly what i want. – Walid Oct 18 '14 at 22:33