Check out my jsFiddle demonstration where I have created a button that adds elements and provides links to delete these elements. Instead of actually deleting the elements in this example, I want to make it so that hovering over the (remove) link, which is generated by clicking the button, highlights the element with the corresponding "number" attribute.
I attempted to use both live();
and on();
for this functionality, but neither worked because the items are added dynamically after the initial page load.
I now prefer using on();
as jQuery has advised:
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().
This is my jQuery code:
function numbers() {
return $('#links span').length;
}
$('#add').on('click', function () {
$('#links').append('<span number="' + (numbers() + 1) + '">Remove element ' + (numbers() + 1) + '</span><br />');
$('#elements').append('<div number="' + numbers() + '" class="element">Element ' + numbers() + '</div>');
});
$('#links span').on('hover', function () {
var number = $(this).attr('number');
if ($('#elements .element').attr('number') == number) {
$(this).addClass('highlight');
}
});