Im using jquery highlighter from this site link. You can select text and highlighter will wrap it in <span>
example
I have problem with registering click event on highlighted part of the text. I have read that on dynamically added elements you have to use .on()
function but I cant manage to make it work.
Here is jsfiddle my code is on the bottom of javascript. I think there is something in the highlighter which blocks the click event but my javascript skills are not good enough to figure out what.
This is how Im trying to register the click event
$(document).ready(function() {
$('#sandbox').textHighlighter();
$('#sandbox').on('click', 'span.highlighted', function(){
alert("Click was registered");
});
});
Two things - you were using an early version of jQuery (1.6.4) that did not support on()
(you could use delegate()
) and your syntax needed to be tweaked slightly -
$(document).on('click', 'span.highlighted', function(){
console.log("Click was registered");
});
Delegation should be done done to an element that exists on the page at the time jQuery originally runs. In this case the event will bubble up to 'document', which safely exists at the time the code runs. The selector could also be '#sandbox'.
One other note, always use console.log()
for trouble-shooting, not alert()
.