Reputation: 239
I have a table and in that table I have given a button to user in first column of every row to delete the row and that delete button is dynamically generated when user enter the mouse on first column and this is the code
$('table').on('mouseover', "td.y-id", function () {
$(this).append($('<a class="dlt-x" style="float: right; cursor: pointer; cursor: hand;"> <i class="fa fa-trash"></i> </a>'));
});
$('table').on('mouseleave', "td.y-id", function () {
$('.dlt-x').remove();
});
and I registered an event to click of delete button like this
$('table').on('click', 'a.dlt-x', function () {
alert("clicked");
});
and this event is not triggering. I look other similar questions and try all the solutions find there related delegated binding but can't solve the problem.
Upvotes: 1
Views: 78
Reputation: 1258
To stop appending the same element append if it does not exist
$(function() {
$('table').on('mouseover', "td.y-id", function (e) {
if ($('.dlt-x').length === 0) {
$(this).append($('<a class="dlt-x" style="float: right; cursor: pointer;">X</a>'));
}
});
$('table').on('mouseleave', "td.y-id", function () {
$('.dlt-x').remove();
});
$('table').on('click', 'a.dlt-x', function () {
alert("clicked");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td class='y-id'>1</td>
</tr>
<tr>
<td class='y-id'>2</td>
</tr>
</table>
Upvotes: 1
Reputation: 59491
Change the event listener to mouseenter
instead. Otherwise you'll keep appending that element if you move the mouse inside.
$('table').on('mouseenter', "td.y-id", function() {
$(this).append($('<a class="dlt-x" style="float: right; cursor: pointer; cursor: hand;"> <i class="fa fa-trash"></i> </a>'));
});
$('table').on('mouseleave', "td.y-id", function() {
$('.dlt-x').remove();
});
$('table').on('click', 'a.dlt-x', function() {
alert("clicked");
});
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>Foo</td>
<td>Bar</td>
<td class="y-id">Delete</td>
</tr>
<tr>
<td>Foo</td>
<td>Bar</td>
<td class="y-id">Delete</td>
</tr>
</table>
Upvotes: 0
Reputation: 403
If you are triggering for dynamic element. Use like below
$('body').on('click',"#dynamic_element_id",function(){
// you code
})
Upvotes: 2