Revenant
Revenant

Reputation: 2984

Jquery, add & remove element on hover

I came a cross a problem which I tried pretty much everything without a solution.

$('a.hovered').hover(function () {
    $(this).after(' <img src="images/icons/famfamfam/silk/user_go.png" />');
},function () {
    $(this).remove(' <img src="images/icons/famfamfam/silk/user_go.png" />');
});

Of course I tried many versions of this remove() without any success. I will be glad if anyone could help me out with this problem.

Additionally I would like to add effect of fadeIn() and fadeOut() but of course this wasn't successful also.

I can add the image but I can't remove it (even fadeIn didn't work while I can successfully add images).

Thank you for your help and time in advance.

Upvotes: 3

Views: 16224

Answers (5)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

.remove() doesn't take a piece of HTML:

$('a.hovered').hover(function () {
    $(this).after(' <img src="images/icons/famfamfam/silk/user_go.png" id="go_image" />');
},function () {
    $('#go_image').remove();
});

Upvotes: 0

Deele
Deele

Reputation: 3684

You cant reference to created object in such manner, try

$('a.hovered').hover(function () {
    $(this).after(' <img src="images/icons/famfamfam/silk/user_go.png" id="addedImage"/>');},
    $('#addedImage').remove();
});

Yep, and while I write, two other post the same stuff :)

Upvotes: 0

Andrew Wilkinson
Andrew Wilkinson

Reputation: 10836

You really don't want to do that. Your code will be quicker, clearer and easier to maintain if you just show and hide an image that always exist.

Just put the img into your html with and id set and style="display: none;" to hide it.

Your javascript code then becomes:

$('a.hovered').hover(function () {
    $("#user_go").show();
},function () {
    $("#user_go").hide();
});

Upvotes: 7

Guy Schaller
Guy Schaller

Reputation: 4700

why not just do this?

$('a.hovered').hover(function () {      
$(this).after(' <img src="images/icons/famfamfam/silk/user_go.png" />');  },
function () {
$(this).find('img').remove();
 });  

Upvotes: -2

Lazarus
Lazarus

Reputation: 43074

Name you elements, it'll make life easier for you, i.e.:

$('a.hovered').hover(function () {
    $(this).after(' <img id="user_go" src="images/icons/famfamfam/silk/user_go.png" />');
},function () {
    $("#user_go").remove();
});

Upvotes: 2

Related Questions