Reputation: 4698
I have a div that when a user hovers over it, I want to add a delete "button" to it. When a user hovers over the div, the tag is inserted at the end of the div. The problem is that the tag is inserted again when the user's mouse leaves the element. I want to remove the tag when the user's mouse leaves the element.
This is the original state of the div:
<div class="tag" data-tag-id="123">hitman</div>
This is what it looks like when I hover over it:
<div class="tag" data-tag-id="123">hitman<div id="delete-123" style="float:right; padding-left:3px;">X</div></div>
When the mouse leaves the element:
<div class="tag" data-tag-id="123">hitman<div id="delete-123" style="float:right; padding-left:3px;">X</div><div id="delete-123" style="float:right; padding-left:3px;">X</div></div>
The "tag" div should go back to it's original state when the mouse leaves it.
This is my jQuery:
$('.tag').hover(function(){
$(this).append('<div id="delete-'+$(this).data('tag-id')+'" style="float:right; padding-left:3px;">'+delete_markup+'</div>');
});
$('.tag').mouseleave(function(){
$(this).remove('[id="delete-'+$(this).data('tag-id')+'"]');
});
Upvotes: 0
Views: 84
Reputation: 9637
hover = mouseenter+mouseleave;
In hover the first function in mouse enter and next function is mouse leave
$('.tag').hover(function () {
$(this).append('<div id="delete-' + $(this).data('tag-id') + '" style="float:right; padding-left:3px;">' + delete_markup + '</div>');
}, function () {
$(this).remove('[id="delete-' + $(this).data('tag-id') + '"]');
});
Description: Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements.
Upvotes: 0
Reputation: 388316
The hover() is a utility to register both mouseenter and mouseleave handlers so can either do
$('.tag').hover(function(){
$(this).append('<div id="delete-'+$(this).data('tag-id')+'" style="float:right; padding-left:3px;">'+delete_markup+'</div>');
}, function(){
$(this).remove('[id="delete-'+$(this).data('tag-id')+'"]');
});
or
$('.tag').mouseenter(function(){
$(this).append('<div id="delete-'+$(this).data('tag-id')+'" style="float:right; padding-left:3px;">'+delete_markup+'</div>');
});
$('.tag').mouseleave(function(){
$(this).remove('[id="delete-'+$(this).data('tag-id')+'"]');
});
If you pass only one callback to hover(handlerInOut) then it is called on both mouseenter
and mouseleave
Demo: Fiddle
Upvotes: 1
Reputation: 85545
You are using mouseleave and hover, just replace hover with mouseenter then it should work fine:
$('.tag').mouseenter(function(){
$(this).append('<div id="delete-'+$(this).data('tag-id')+'" style="float:right; padding-left:3px;">'+delete_markup+'</div>');
});
$('.tag').mouseleave(function(){
$(this).remove('[id="delete-'+$(this).data('tag-id')+'"]');
});
Or you can use mouseleave function in hover method as second function.
Upvotes: 0