JQuery - how to undo

I use the prepend () function to diplay the image when the div is expanded. How to delete an image - that is, the opposite of prepend ()

Here is the code:

$("#hover-div").hover( function() { $("#image-div").prepend("<img src='images/arrow_redo.png' width='16' height='16' />"); }, function() { $("#image-div").someFunction("<img src='images/arrow_redo.png' width='16' height='16' />"); } ); 

someFunction is just a mannequin - I do not expect him to do anything.

+4
source share
7 answers

If you have an image element identifier, you can simply use the remove method.

 $("#imgID").remove(); 
+5
source

try prependTo instead of prepend - let me demonstrate:

 var img; $("#hover-div").hover( function() { img = $("<img src='images/arrow_redo.png' width='16' height='16' />").prependTo("#image-div"); }, function() { img.remove(); } ); 

This allows you to create a variable that contains a link to your image so that you can manipulate it after adding it.

Hope this helps

+3
source

What if you save the contents of node in a variable before applying prepend ()?

+1
source

This is probably the best way to handle this - plus I think it is going to preload the image for you anyway as an added bonus (albeit not a positive one).

 var $img = $("<img src='images/arrow_redo.png' width='16' height='16' />"); $('#hover-div').hover(function() { $('#image-div').prepend($img); }, function() { $img.remove(); }); 

Otherwise:

 $(this).children().eq(0).remove(); 

will find the first child and remove it. However, be careful if the event occurs twice, it can delete more than just your image.

+1
source
 $("#image-div").prev().remove(); 

This will select the previous item and delete it.

0
source

Does he prefer the best option initially? Keep in mind that DOM manipulation can be expensive, so anything you can do to mitigate this would be nice

It looks like you better have the image in the background and switch it when you hover over a div.

Sort of:

 $("#MyDiv").mouseover(function(){ $(this).find("img").toggle(); }); $("#MyDiv").mouseout(function(){ $(this).find("img").toggle(); }); 

Or, conversely, use .hover

This is not tested and can be reorganized to be better, but with the idea of ​​what I get, I hope!

0
source

You can add an attribute to the added elements and find them later for additional ...

 $("#hover-div").hover( function() { $("<img src='image.png' />").prependTo("#image-div").attr('prepended','yes'); }, function() { $("[prepended=yes]", "#image-div").remove(); } ); 
0
source

All Articles