Reputation: 121
I have a working tooltip jQuery script:
HTML:
<div style="display:none;" class="tooltipcontent">
<p class="para">Your VIN needs to be:</p>
<ul class="vinhelp">
<li>Exactly 17 characters for a vehicle manufactured after 1980 (1981 or later model year.)</li>
<li>Without the letters I, O, or Q.</li>
</ul>
</div> <span class="questinfo">test</span>
jQuery:
jQuery('.questinfo').hover(function () {
// Hover over code
var title = jQuery('.tooltipcontent').html();
if (title) {
jQuery('<p class="tooltip"></p>')
.html(title)
.appendTo('body')
.fadeIn('slow');
}
}, function () {
// Hover out code
jQuery('.tooltip').remove();
}).mousemove(function (e) {
var mousex = e.pageX + 20; //Get X coordinates
var mousey = e.pageY + 10; //Get Y coordinates
jQuery('.tooltip')
.css({
top: mousey,
left: mousex
})
});
Working JSFIDDLE: http://jsfiddle.net/z3cnmf6p/1/
Note: it is not jquery Ui tooltip.
Problem: This script works fine but my requirement is to bind the hover function to a dynamically created element by jQuery for that purpose I tried jQuery .on() instead of .hover(), but it does not work:
Here is what I have tried:
Upvotes: 1
Views: 1312
Reputation: 16184
It seems redundant create .tooltip
from .tooltipcontent
- why not just show and hide that? EG: http://jsfiddle.net/vh5670cy/1/
// creating a new span with class 'questinfo' dynamically.
$("#result").html('<span class="questinfo">Test</span>');
// Bind delegated hover events to a parent
$("body")
.on("mouseover", ".questinfo", function(e){
$('.tooltip').fadeIn('fast');
})
.on("mouseout", ".questinfo", function(e){
$('.tooltip').hide();
})
.on("mousemove", ".questinfo", function(e){
$('.tooltip').css({
top: e.pageY + 10,
left: e.pageX + 10
})
});
.tooltip {
background:black;
padding:15px;
color:white;
position:absolute;
/* etc */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="display:none;" class="tooltip">
<p class="para">Your VIN needs to be:</p>
<ul class="vinhelp">
<li>Exactly 17 characters for a vehicle manufactured after 1980 (1981 or later model year.)</li>
<li>Without the letters I, O, or Q.</li>
</ul>
</div>
<div id="result"></div>
Upvotes: 2
Reputation: 6933
Try it like this http://jsfiddle.net/vp3vqtk8/1/
// creating a new span with class 'questinfo' dynamically.
jQuery("#result").html('<span class="questinfo">Test</span>');
// Binding hover event to the dynamically created span element
$(document).on("mouseenter", '.questinfo', function () {
var title = jQuery('.tooltipcontent').html();
if (title.length) {
jQuery('<p class="tooltip"></p>')
.html(title)
.appendTo('body')
.fadeIn('slow');
}
}).mousemove(function (e) {
var mousex = e.pageX + 20; //Get X coordinates
var mousey = e.pageY + 10; //Get Y coordinates
$('.tooltip')
.css({
top: mousey,
left: mousex
});
});
$(document).on('mouseleave', '.questinfo', function() {
$('body').find('.tooltip').remove();
});
Upvotes: 2