So this is the functionality I need to clean up:
I need to create a function where viewers can click on any word in a sentence, and it will be highlighted. However,
As per @DrewGoldsBerry's answer, with some example code. Here's a working fiddle of the code below: http://jsfiddle.net/E3D6T/1/
Set up your HTML with a class to indicate which lines should have the highlight functionality.
Each word will be wrapped in a span.
A second paragraph here.
In your JS, split the p
elements into words wrapped in span
tags, which can then be bound to a click function:
// wrap words in spans
$('p.highlight').each(function () {
var $this = $(this);
$this.html($this.text().replace(/\b(\w+)\b/g, "$1"));
});
// bind to each span
$('p.highlight span').click(function () {
$(this).parent().find('span').css('background-color', '');
$(this).css('background-color', '#ffff66');
});
edit:
http://jsfiddle.net/jorgthuijls/E3D6T/16/
I added all the answer checking to the click function itself. Should be fairly straight forward.