Felix Felix - 1 month ago 6
CSS Question

How to make a close button for each image inside the div using CSS and js

How to make close button for each images on hover? There is a div in which each image is draggable.

I need to make a close button near to each image. That button
need to visible only when we touch or moving mouse pointer on the image, that is the button need to show in it's hover effect.

This is my HTML



$( function() {
var a = 1;
$( ".child" ).draggable({
containment: "parent",
start: function(event, ui) { $(this).css("z-index", a++); }
});
} );

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>
<div class="parent" style="z-index:1; min-height: 200px; background-image: url('http://img.freepik.com/free-vector/white-canvas-background_1053-239.jpg?size=338&ext=jpg')">
<img src ='https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/128x128/Circle_Red.png' style='position: absolute; z-index:1' class='child' />
<img src =' https://cdn2.iconfinder.com/data/icons/free-color-halloween-icons/24/Wand-128.png' style='position: absolute; z-index:1' class='child' />

<img src =' https://cdn2.iconfinder.com/data/icons/free-color-halloween-icons/24/Candy-01-128.png' style='position: absolute; z-index:1' class='child' />

</div>





JSFiddle demo

I know how to remove that image using jquery.
for example the code like this

$(document).on("click",".closeButton",function(){
$(this).closest('.child').remove();
});

Answer

Wrap each image with separate div, add .child class to that div instead of image:

<div class="parent">
  <div class='child'>
    <img src ='https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/128x128/Circle_Red.png' />
  </div>
  <div class='child'>
    <img src ='https://cdn2.iconfinder.com/data/icons/free-color-halloween-icons/24/Wand-128.png' />
  </div>
  <div class='child'>
    <img src ='https://cdn2.iconfinder.com/data/icons/free-color-halloween-icons/24/Candy-01-128.png' />
  </div>
</div>

and then:

var a = 1;
$( ".child" ).draggable({
  containment: "parent",
  start: function(event, ui) { $(this).css("z-index", a++); }
}).hover(function(){
  $(this).prepend('<button class="remove">x</button>');
}, function(){
  $(this).find('.remove').remove();
}).on('click', '.remove', function(){
  $(this).closest('.child').remove();
});

JSFiddle Demo