I have the jQuery function below which alters the CSS on hover of a p element.
$("p").hover (
function() {$(this).addClass("choice"); } ,
function() { $(this).removeClass("choice");} );
The problem is that it will not function for the innerHTML of a div written with .html() or .append(), like so
$('#div').html('<p>content that needs to highlight on hover</p>');
Even if I try to insert the function itself to that innerHTML like so
$('#div').append('<script type="text/javscript">$("p").hover ( function() {$(this).addClass("choice"); } , function() { $(this).removeClass("choice");} );<'+'/script>');
it will still not function for the HTML content of that div.
What am I missing here? Thanks, any help would be much appreciated.
When you write
$("p").hover, that does a one-time search of the current state of the document, finds all<p>tags and attached event handlers to them. It will not attach event handlers to<p>tags you add to the document in the future.If you want to have event handlers for future
<p>tags, then you need to use.delegate()(for pre-jQuery 1.7) or.on()(for jQuery 1.7+).With jQuery 1.7+, it would work like this:
You have to use mouseover and mouseout events because
hoverwith two separate callback functions is not supported with.on()(at least it wasn’t the last time I checked).Ideally, you wouldn’t use document.body in this code, but would use some common parent element that is not dynamic (it’s already there and stays there) and is as close in the hierarchy to the
<p>tags that you’re monitoring as possible. This keeps too many events from having to bubble all the way up to the document level and helps with performance.