Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append a delete image/icon to image inside div using jquery

Tags:

html

jquery

image

I am trying to upload some images and display them inside an empty DIV and after uploading if I mouse hover on an image I should get a delete icon so that users should be able to delete it with an animation and move the next image to the deleted image position.

How do I achieve that?

This is how I am uploading and appending to the div container:

<script type="text/javascript">
 $(function () {
     document.getElementById('Nextbutton').style.visibility = "hidden"; // show 
     $("#uploader").plupload({
         // General settings
         runtimes: 'gears,flash,silverlight,browserplus,html5',
         url: 'Test.aspx',
         max_file_size: '10mb',
         max_file_count: 20,
         chunk_size: '1mb',
         unique_names: true,

         filters: [
            { title: "Image files", extensions: "jpg,gif,png" },
            { title: "Zip files", extensions: "zip" }
        ],


         flash_swf_url: 'js/plupload.flash.swf',


         silverlight_xap_url: 'js/plupload.silverlight.xap'
     });



     $('form').submit(function (e) {
         var uploader = $('#uploader').plupload('getUploader');

         if (uploader.files.length > 0) {

             uploader.bind('StateChanged', function () {
                 if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
                     $('form')[0].submit();
                 }
             });

             uploader.start();

         }
         else
         //alert('You must at least upload one file.');

             return false;
     });
     var uploader = $('#uploader').plupload('getUploader');

     uploader.bind('FilesAdded', function (up, files) {
         //              jQuery('#container a').html('');
         $('#container > *').remove();
         var i = 0;
         while (i++ < up.files.length) {
             var ii = i;
             while (ii < up.files.length) {
                 if (up.files[i - 1].name == up.files[ii].name) {
                     $.msgBox({
                         title: "Ooops",
                         content: "There is already an image with the same filename and cannot be added.",
                         type: "error",
                         showButtons: true,
                         opacity: 0.9,
                         autoClose: false
                     });
                     uploader.removeFile(up.files[ii]);
                 } else {
                     ii++;
                 }
             }
         }
         if (i > 20) {
             $.msgBox({
                 title: "Info",
                 content: "Uuh! Please don't put me any more files.<br>Maximum Upload limit is only 20 Images.<br>Rest of the Images will be removed.",
                 type: "info",
                 showButtons: true,
                 opacity: 0.9,
                 autoClose: false
             });
             $('#uploader_browse').hide();
         }
     });
     uploader.bind('FilesRemoved', function (up, files) {
         if (up.files.length < 20) {
             $('#uploader_browse').fadeIn("slow");
         }
     });


     uploader.bind('FileUploaded', function (up, file, res) {
         $('#container').append("<div class='container a'><a href='uploads/" + document.getElementById("currentDirectory").value + "/" + file.name + "'  rel='prettyPhoto' target='blank'><img src='uploads/" + document.getElementById("currentDirectory").value + "/" + file.name + "' width='64' height='64'/></a></div>");



         var $imageContainers = $('#container a');

         $imageContainers.each(function (index) {
             $(this).delay(index * 50).fadeTo(400, 0.5);
         });

         $imageContainers.mouseover(function () {
             $(this).css('opacity', 1);
             $(this).find('span.del').show();
         });
         $imageContainers.mouseout(function () {
             $(this).css('opacity', 0.5);
             $(this).find('span.del').hide();
         });



         if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
             document.getElementById('Nextbutton').style.visibility = "visible"; // show 
             showStickySuccessToast();
         }
         uploader.removeFile(file);
     });

 });


     function randomString(length) {
         var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split('');

         if (!length) {
             length = Math.floor(Math.random() * chars.length);
         }

         var str = '';
         for (var i = 0; i < length; i++) {
             str += chars[Math.floor(Math.random() * chars.length)];
         }
         return str;
     }

    </script>

Here is my div where I am showing the Images:

<div id="container">
</div>   
like image 382
coder Avatar asked Nov 09 '11 11:11

coder


2 Answers

A demo is available at: http://jsfiddle.net/CWaHL/1/

HTML

<div id="container">
  <div class="image" id="image1" style="background-image:url(http://lorempixel.com/100/100/abstract);">
    <a href="#" class="delete">Delete</a>
  </div>
  <div class="image" id="image2" style="background-image:url(http://lorempixel.com/100/100/food);">
    <a href="#" class="delete">Delete</a>
  </div>
  <div class="image" id="image3" style="background-image:url(http://lorempixel.com/100/100/people);">
    <a href="#" class="delete">Delete</a>
  </div>
  <div class="image" id="image4" style="background-image:url(http://lorempixel.com/100/100/technics);">
    <a href="#" class="delete">Delete</a>
  </div>
</div>

CSS

#container { overflow:auto; }
.image { width:100px;height:100px;float:left;position:relative; }
a.delete { display:none;position:absolute;top:0;right:0;width:30px;height:30px;text-indent:-999px;background:red; }
.image:hover a.delete { display:block; }

jQuery/Javascript

$(document).ready(function(){

  $('a.delete').on('click',function(e){
    e.preventDefault();
    imageID = $(this).closest('.image')[0].id;
    alert('Now deleting "'+imageID+'"');
    $(this).closest('.image')
      .fadeTo(300,0,function(){
        $(this)
          .animate({width:0},200,function(){
            $(this)
              .remove();
          });
      });
  });

});
like image 131
Luke Stevenson Avatar answered Oct 19 '22 22:10

Luke Stevenson


in this case you can set identifier like id ,class or name in tag img or where tag you want to bind event mouseover. this is script you do:

uploader.bind('FileUploaded', function (up, file, res)
         {
         $('#container').append("<div class='container a'>
         <a href='uploads/" + document.getElementById("currentDirectory").value 
         + "/" + file.name + "'  rel='prettyPhoto' target='blank'>
         <img class="img-upload" src='uploads/" + document.getElementById("currentDirectory").value + "/" 
         + file.name + "' width='64' height='64'/>
         </a>
         </div>"
}
);

i'm adding class="img-upload" in img tag , and will be use in next step.after this you must add listener for search your class element. because your element image not generate when browser execute javascript in first time.example in document.ready. the element will be generate after you upload image , that is cannot make event onmouseevent in document.ready because the dom is undefined.

my solution is : 1) make event delegate or live example: you add this code in you script

$(".container ").delegate(".img-upload", "mouseover", function() {
  // show notification delete like icon
}); 

or if that is not work you can try this

$(".img-upload").live("mouseover", function(){ alert("get mouse over event"); }); 

and if you want to use timeout to search element live or not, you can try this you must add id in you code like this.

uploader.bind('FileUploaded', function (up, file, res)
             {
             $('#container').append("<div class='container a'>
             <a href='uploads/" + document.getElementById("currentDirectory").value 
             + "/" + file.name + "'  rel='prettyPhoto' target='blank'>
             <img id="img-upload" src='uploads/" + document.getElementById("currentDirectory").value + "/" 
             + file.name + "' width='64' height='64'/>
             </a>
             </div>"
    }
    );


function waitForImg(){
var ele = document.getElementById(idImg);
 if(!ele){
  window.setTimeout(waitForImg, 100);
 }
 else{
  //you can show delete in here 
  $('#img-upload').mouseover(function() {
    //show image delete 
    alert('show your icon delete');
 });
 }
}
waitForImg();
like image 33
viyancs Avatar answered Oct 19 '22 21:10

viyancs