Home > Enterprise >  drag drop than removing files
drag drop than removing files

Time:10-29

I used javascript to drag&drop multi files. than I am showing those images. Below is fully runable with no errors

Need help with: I want ability to remove those image as well. Please take a look at attached image below, I want to create [x] buttons at top right on image. if click on [x] than it will remove image depending on which [x] you click. close is in drop function below

enter image description here

below is my javascript so far. need help in drop function

        var dropZone = document.getElementById('dropZone');
        var details = document.querySelector('#imgDetail');
    
        ///////////
        // dragover
        ///////////
        dropZone.addEventListener('dragover', function (e) {
            e.stopPropagation();
            e.preventDefault();
            e.dataTransfer.dropEffect = 'copy';
            document.getElementById('dropZone').classList.add("hoverActive");
        });
    
        /////////////
        //drag leave 
        /////////////
        dropZone.addEventListener('dragleave', function (e) {
            document.getElementById('dropZone').classList.remove("hoverActive");
        });
    
        ////////////
        // drop file
        ////////////
        dropZone.addEventListener('drop', (e) => {
            document.getElementById('dropZone').classList.remove("hoverActive");
            document.getElementById('BackgroundText').style.visibility = "hidden";
            e.stopPropagation();
            e.preventDefault();
    
            details.innerHTML = '';
            var files = e.dataTransfer.files;
    
            Object.values(files).forEach((file) => {
                var reader = new FileReader();
    
                reader.onloadend = () => {
                    //display image
                    var img = document.createElement('img');
                    img.src = reader.result;
                    img.style.paddingRight = 5;
                    img.width = 150;
                    img.height = 150;
                    img.border = 2;
    
                    var div = document.getElementById('imageHold')
                    div.appendChild(img);
    
                    //create button
                    div.innerHTML  = '<button id="btn" name="btn">X</button>';
    
                    //display file name
                    details.innerHTML  = `<p>Name: ${file.name}<p>';
    
                    //details.innerHTML  = <p>Size: ${bytesToSize(file.size)}</p>`;
                };
                reader.readAsDataURL(file);
            });
        });
    
        function bytesToSize(bytes) {
            var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
            if (bytes == 0) return '0 Byte';
            var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
            return Math.round(bytes / Math.pow(1024, i), 2)   ' '   sizes[i];
        }
    
    
      #dropZone
    {
      border: 2px dashed gray;
      height: 200px;
      width: auto;
      border-radius: 5px;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
    }
    #dropZone header{
      font-size: 20px;
      font-weight:bold;
    }

.hoverActive{
 border: 2px dashed darkred !important;
}
   <br /><br />

    <div class="container">
        <div class="row">
            <div>
                <div id="dropZone">
                    <div class="icon"><i class="fas fa-cloud-upload-alt"></i></div>
                    <header id="BackgroundText">Drag & Drop to Upload File</header>
                    <div id="imageHold" style="float:left;">
                    </div>
                </div>
            </div>
        </div>
    </div>


    <div id="imgDetail">test</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

html code

CodePudding user response:

Demo Page

HTML:

div.innerHTML  = '<button id="btn" name="btn" onclick=removeImage_and_btn(this)>X</button>';

You could use previousSibling to get the previous element

JS:

function removeImage_and_btn(el){        
    if(!el.previousSibling.tagName){//if it is textnode like newline etc. we go one back 
        var el = el.previousSibling;
    }
    if(el.previousSibling.tagName && el.previousSibling.tagName=='IMG'){
        el.previousSibling.remove();
        el.remove();
    }
}

CodePudding user response:

        var dropZone = document.getElementById('dropZone');
        var details = document.querySelector('#imgDetail');
    
        ///////////
        // dragover
        ///////////
        dropZone.addEventListener('dragover', function (e) {
            e.stopPropagation();
            e.preventDefault();
            e.dataTransfer.dropEffect = 'copy';
            document.getElementById('dropZone').classList.add("hoverActive");
        });
    
        /////////////
        //drag leave 
        /////////////
        dropZone.addEventListener('dragleave', function (e) {
            document.getElementById('dropZone').classList.remove("hoverActive");
        });
    
        ////////////
        // drop file
        ////////////
        dropZone.addEventListener('drop', (e) => {
            document.getElementById('dropZone').classList.remove("hoverActive");
            document.getElementById('BackgroundText').style.visibility = "hidden";
            e.stopPropagation();
            e.preventDefault();
    
            details.innerHTML = '';
            var files = e.dataTransfer.files;
    
            Object.values(files).forEach((file) => {
                var reader = new FileReader();
    
                reader.onloadend = () => {
                    //create frame elem section
                    let dv = document.createElement('div');
                    dv.style.cssText = `
                        display: inline-block;
                        position: relative; 
                        width: 150px; 
                        height: 150px; 
                        border: 1px #ddd solid;
                        margin-right: 5px;
                    `;

                    //create image elem
                    var img = document.createElement('img');
                    img.src = reader.result;
                    // optional 100%
                    // img.style.width = "100%"; 
                    img.style.width = "150px";
                    img.style.height= "150px";
                    
                    //add img to frame 
                    dv.append(img);

                    //create btn remove
                    let btn = document.createElement('button');
                    btn.innerHTML = "x";
                    btn.style.cssText = `
                        position: absolute; 
                        right: 2px; 
                        top:2px;
                    `;
    
                    //add btn to frame 
                    dv.append(btn);

                    //set frame to target elem
                    document.getElementById('imageHold').append(dv);
                    
                    //set event btn and exec remove frame
                    btn.addEventListener('click', e => {
                        e.target.parentElement.remove();
                    });
                    
    
                    //display file name
                    details.innerHTML  = `<p>Name: ${file.name}<p>';
    
                    //details.innerHTML  = <p>Size: ${bytesToSize(file.size)}</p>`;
                };
                reader.readAsDataURL(file);
            });
        });
    
        function bytesToSize(bytes) {
            var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
            if (bytes == 0) return '0 Byte';
            var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
            return Math.round(bytes / Math.pow(1024, i), 2)   ' '   sizes[i];
        }
    
    
      #dropZone
    {
      border: 2px dashed gray;
      height: 200px;
      width: auto;
      border-radius: 5px;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
    }
    #dropZone header{
      font-size: 20px;
      font-weight:bold;
    }

.hoverActive{
 border: 2px dashed darkred !important;
}
   <br /><br />

    <div class="container">
        <div class="row">
            <div>
                <div id="dropZone">
                    <div class="icon"><i class="fas fa-cloud-upload-alt"></i></div>
                    <header id="BackgroundText">Drag & Drop to Upload File</header>
                    <div id="imageHold" style="float:left;">
                    </div>
                </div>
            </div>
        </div>
    </div>


    <div id="imgDetail">test</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related