Jquery, add & remove element on hover

15,686

Solution 1

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();
});

Solution 2

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();
});
Share:
15,686
Revenant
Author by

Revenant

Updated on June 04, 2022

Comments

  • Revenant
    Revenant about 2 years

    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.