Reputation: 2126
I am creating a div dynamically, then appending it to a container:
var str = '<div class="dimsdiv" id="'+dim.src+'" cursor:pointer;"></div>';
$('#fpdiv').append(str);
Now I need to add a hover even to those divs. I tried to just reference it, but then found that I needed to consider .on() instead. I tried this (before on):
$('#'+dim.src).hover(function{},function{});
But as expected, that didn't work. I also tried this:
$('#'+dim.src).on('hover','(function{},function{})');
but can't seem to get the syntax just right. Can someone help here? Thanks in advance.
Upvotes: 1
Views: 238
Reputation: 146191
You may try this
var str = $('<div/>', {
text:'Hello',
class:'dimsdiv',
id:'dim_src',
style:'cursor:pointer',
mouseenter:function(){ ... },
mouseleave:function(){ ... }
});
$('#fpdiv').append(str);
Also remove the .
from dim.src
, instead use dim_src
as id
, it's used as class
selector in jQuery, not sure why you used it tho but $('#'+dim.src)
is invalid.
DEMO.
Upvotes: 3
Reputation: 1142
What you need is a live function so you can set it once and it will affect your dynamic html.
Upvotes: 0
Reputation: 1033
The shorthand hover
alias for on
was removed in 1.8. You can use the hover()
method instead. It accepts one or two functions as arguments to handle the hover-in and hover-out events.
$('#'+dim.src).hover(
function () {
// hover in code here
},
function () {
// hover out code here
}
);
Upvotes: 0
Reputation: 145398
You can use delegated-events approach and bind hover events (i.e. mouseenter
and mouseleave
) for dynamically created elements with class "dimsdiv" and parent element with ID "fpdiv":
$("#fpdiv").on({
mouseenter : function() {
// hover on
},
mouseleave : function() {
// hover off
}
}, ".dimsdiv");
Upvotes: 2
Reputation: 55740
.on('hover',' has been deprecated in the latest jQuery version..
You need to use delegated events to do that.. Add the events to the parent container .
The second approach is to add the events once the element is created
$(function() {
var addEvent = function() {
$('.dimsdiv').unbind().hover(function {}, function {});
}
// Lets say you are creating your div's here
$('#btn').on('click', function() {
// Create Div
var str = '<div class="dimsdiv" id="'+dim.src+'" cursor:pointer;"></div>';
$('#fpdiv').append(str);
// Call the function here
addEvent();
});
});
Upvotes: 0