Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript code for remove image

I want to make this Javascript code to when I click "remove image" link , it remove the image. Please help me.

<script>
function previewFile(){

   var preview = document.querySelector('img'); 
   var file    = document.querySelector('input[type=file]').files[0];
   var reader  = new FileReader();

   reader.onloadend = function () {
       preview.src = reader.result;
   }
   if (file) {
       reader.readAsDataURL(file); 
   } else {
       preview.src = "";
   }
}

  previewFile();  

</script>

<input type="file" onchange="previewFile()"><br>
<img src="" height="200" alt="Image preview...">
<a href="#">remove image </a>

  </body>
</html>
like image 791
user3732708 Avatar asked Nov 01 '22 06:11

user3732708


2 Answers

<img id='image' src="" height="200" alt="Image preview...">
<a id='remove' href="#">remove image </a>

<script>
$(function rmv() {
    $('#remove').click(function() {
            $('#image').remove();
        }

}); 
</script>
like image 198
Mahmoud Ksemtini Avatar answered Nov 12 '22 15:11

Mahmoud Ksemtini


If you cannot add id attribute to that img, you can remove it like this with raw javascript - it assumes the image is preceding the anchor tag directly, allowing for only one text node between them:

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

<img src="" height="200" alt="Image preview...">
<a href="#" onclick="removeImage(this);">remove image</a>
like image 44
n-dru Avatar answered Nov 12 '22 15:11

n-dru