How can i delete images preview each time file input is clicked? - javascript

I'm trying to reset the image preview created by file input each time the upload button clicks. I'm new to JS so forgive me if I missed the obvious.
This is a code snippet I found to show the preview:
$(function() {
var imagesPreview = function(input, placeToInsertImagePreview) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img class="padit">')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
}
reader.readAsDataURL(input.files[i]);
}
}
};
$('#gallery-photo-add').on('change', function() {
imagesPreview(this, 'div.gallery');
});
});
This is my HTML:
<div class="upload-field">
<label class="bcard-label" for="gallery-photo-add">
<input id="gallery-photo-add" type="file" accept="image/*" value="" multiple>
<i class="fa fa-2x fa-camera"></i>
</label>
</div>
<div class="gallery">
</div>
This is the CSS:
.upload-field{
display: flex;
justify-content: center;
align-items: center;
max-width: 95%;
border: 4px dashed grey;
height: 100px;
margin: auto;
}
.gallery{
display: inline-block;
column-count: 2;
margin: 15px;
}
img.padit{
padding: 5px;
}
And with my very little knowledge in JS I tried to complete the task with this snippet:
const element = document.getElementById("gallery-photo-add");
element.addEventListener("click", function() {
document.getElementById("padit").remove();
Any ideas where am I wrong?
Thanks :)

Related

drag drop than removing files

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
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>
html code
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>
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();
}
}

change event is not fired on Microsoft Edge on first click

I am trying to implement drag and drop and browse files. I have a <div> with id #box and trying to trigger <input type="file" id="imageUpload" /> on click event of that <div>. The following code is working fine on Mozilla Firefox and Google Chrome but having problem on Microsoft Edge.
$(document).off().on('click', '#box', function () {
$('#imageUpload').trigger('click');
$('#imageUpload').off().on('change', function () {
var imageLoader = document.getElementById('imageUpload');
selectedFiles = imageLoader.files;
imageBrowseUploader(selectedFiles);
});
});
#box {
border: 1px dotted #0B85A1;
width: 100%;
height: 150px;
color: #92AAB0;
text-align: center;
font-weight: 500;
}
#imageUpload {
visibility: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="box">
<b>Drag and drop or click here</b> to upload your image.
</div>
<input type="file" id="imageUpload" />
Here is the working Demo with minor changes! (As you can see)
$(document).ready(function(){
$(document).on('click', '#box', function () {
//debugger;
$('#imageUpload').trigger('click');
});
$(document).on('change', function () {
debugger;
var imageLoader = document.getElementById('imageUpload');
selectedFiles = imageLoader.files[0].name;
imageBrowseUploader(selectedFiles);
});
});
function imageBrowseUploader(selectedFiles)
{
alert(selectedFiles);
}
#box {
border: 1px dotted #0B85A1;
width: 100%;
height: 150px;
color: #92AAB0;
text-align: center;
font-weight: 500;
}
#imageUpload {
visibility: hidden;
}
<html>
<head>
<!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>
<div id="box">
<b>Drag and drop or click here</b> to upload your image.
</div>
<input type="file" id="imageUpload" />
</body>
</html>
Hope this will works for you! thank you :)
I would put the on change outside the click function, like this:
$(document).ready(function(){
$(document).off().on('click', '#box', function () {
$('#imageUpload').trigger('click');
});
$('#imageUpload').off().on('change', function () {
var imageLoader = document.getElementById('imageUpload');
selectedFiles = imageLoader.files;
imageBrowseUploader(selectedFiles);
});
});
#box {
border: 1px dotted #0B85A1;
width: 100%;
height: 150px;
color: #92AAB0;
text-align: center;
font-weight: 500;
}
#imageUpload {
visibility: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="box">
<b>Drag and drop or click here</b> to upload your image.
</div>
<input type="file" id="imageUpload" />
$(document).off().on('click', '#box', function () {
$('#imageUpload').trigger('click');
$('#imageUpload').off().on('change', function () {
var imageLoader = document.getElementById('imageUpload');
selectedFiles = imageLoader.files;
imageBrowseUploader(selectedFiles);
});
});
#box {
border: 1px dotted #0B85A1;
width: 100%;
height: 150px;
color: #92AAB0;
text-align: center;
font-weight: 500;
}
#imageUpload {
visibility: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="box">
<b>Drag and drop or click here</b> to upload your image.
</div>
<input type="file" id="imageUpload" />
Your above function contains event inside event.Please don't do that and initialize your change function inside document.ready function()

How to replace my Grid with the new one

With this i can make a gird like 3x3 but if i want to make a new one it will stack on the old grid so how do i remove the old grid so i can see the new one?
Example of this:
I type 3 into row and column and click the button it will then make a grid 3x3.
Then i will try again and make the grid 5x5 so i type 5 into row and column but it just stack it on the old grid so how do i replace it with the new grid?
$(document).on("click","#gridBtn",function()
{
// Cal the size of the Main div
var mapHeight = $("#theMap").height(); // 400
var mapWidth = $("#theMap").width(); // 400
// divide it BY
var rowsLeft = $("#rowValue").val();
var columnsTop = $("#columnValue").val();
// Cal the size of the box
var divideHeight = mapHeight / columnsTop; // 100
var divideWidth = mapWidth / rowsLeft; // 100
for (var i = 0; i < rowsLeft; i++) {
$("#theMap").append('<div class="row" style="height:'+divideHeight+'px; width: auto;"></div>');
}
for (var i = 0; i < columnsTop; i++) {
$(".row").append('<div class="square" style="height:'+divideHeight+'px; width:'+divideWidth+'px;"></div>');
}
});
#wrapper {
height: 100vh;
display: flex;
justify-content: space-around;
align-items: center;
flex-direction: column;
}
#theMap {
background-color: gray;
height: 90px;
width: 90px;
}
.square {
display: inline-block;
box-shadow: 0 0 0 1px gold inset;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
<div id="theMap"></div>
<div id="inputWrapper">
<input id="rowValue" type="text" placeholder="rows">
<input id="columnValue" type="text" placeholder="columns">
<button id="gridBtn">Create grid</button>
</div>
</div>
I simply added $("#theMap").html(""); to the start of the function, to clearthe contents of #theMap. Is this what you are wanting?
$(document).on("click","#gridBtn",function()
{
$("#theMap").html("");
// Cal the size of the Main div
var mapHeight = $("#theMap").height(); // 400
var mapWidth = $("#theMap").width(); // 400
// divide it BY
var rowsLeft = $("#rowValue").val();
var columnsTop = $("#columnValue").val();
// Cal the size of the box
var divideHeight = mapHeight / columnsTop; // 100
var divideWidth = mapWidth / rowsLeft; // 100
for (var i = 0; i < rowsLeft; i++) {
$("#theMap").append('<div class="row" style="height:'+divideHeight+'px; width: auto;"></div>');
}
for (var i = 0; i < columnsTop; i++) {
$(".row").append('<div class="square" style="height:'+divideHeight+'px; width:'+divideWidth+'px;"></div>');
}
});
#wrapper {
height: 100vh;
display: flex;
justify-content: space-around;
align-items: center;
flex-direction: column;
}
#theMap {
background-color: gray;
height: 90px;
width: 90px;
}
.square {
display: inline-block;
box-shadow: 0 0 0 1px gold inset;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
<div id="theMap"></div>
<div id="inputWrapper">
<input id="rowValue" type="text" placeholder="rows">
<input id="columnValue" type="text" placeholder="columns">
<button id="gridBtn">Create grid</button>
</div>
</div>
You need to clean the previous "created table" before create a new one, I would try something like:
$("#theMap").val(''); // cleans before append again
$(".row").val(''); // cleans before append again

Image Upload with preview and Delete option - Javascript / Jquery

I have code below that runs perfectly and uploads multiple images.
This is the html and jQuery code:
<div class="field" align="left">
<span>
<h3>Upload your images</h3>
<input type="file" id="files" name="files[]" multiple />
</span>
</div>
The script is as below:
<style>
input[type="file"] {
display:block;
}
.imageThumb {
max-height: 75px;
border: 2px solid;
margin: 10px 10px 0 0;
padding: 1px;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
if(window.File && window.FileList && window.FileReader) {
$("#files").on("change",function(e) {
var files = e.target.files ,
filesLength = files.length ;
for (var i = 0; i < filesLength ; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
$("<img></img>",{
class : "imageThumb",
src : e.target.result,
title : file.name
}).insertAfter("#files");
});
fileReader.readAsDataURL(f);
}
});
} else { alert("Your browser doesn't support to File API") }
});
</script>
The code adds multiple images and shows previews of the images too. But now I want that when a user clicks on some button, lets say delete on every image uploaded, it should be removed. Not hidden.
Any help to this will be appreciated!
Try adding this : .click(function(){$(this).remove();});. It will remove the image by clicking it.
EDIT Improved version included.
EDIT 2 Since people keep asking, please see this answer on manually deleting a file from a FileList (spoiler: it's not possible...).
$(document).ready(function() {
if (window.File && window.FileList && window.FileReader) {
$("#files").on("change", function(e) {
var files = e.target.files,
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
$("<span class=\"pip\">" +
"<img class=\"imageThumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
"<br/><span class=\"remove\">Remove image</span>" +
"</span>").insertAfter("#files");
$(".remove").click(function(){
$(this).parent(".pip").remove();
});
// Old code here
/*$("<img></img>", {
class: "imageThumb",
src: e.target.result,
title: file.name + " | Click to remove"
}).insertAfter("#files").click(function(){$(this).remove();});*/
});
fileReader.readAsDataURL(f);
}
});
} else {
alert("Your browser doesn't support to File API")
}
});
input[type="file"] {
display: block;
}
.imageThumb {
max-height: 75px;
border: 2px solid;
padding: 1px;
cursor: pointer;
}
.pip {
display: inline-block;
margin: 10px 10px 0 0;
}
.remove {
display: block;
background: #444;
border: 1px solid black;
color: white;
text-align: center;
cursor: pointer;
}
.remove:hover {
background: white;
color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="field" align="left">
<h3>Upload your images</h3>
<input type="file" id="files" name="files[]" multiple />
</div>
Use this for remove files values and file preview
$(".remove").click(function(){
$(this).parent(".pip").remove();
$('#files').val("");
});`

HTML5 drag&drop ignore drop and opens file

I am trying to open a text file via drag&drop and simple open file button. I managed to get my button working, but have some problems with the drag-drop. As i am droping the file on my dropdown area the file gets opened and is read by the browser not my js-code.
#fileInput {
display: none;
}
#dropBox {
margin: 15px;
width: 300px;
height: 300px;
border: 5px dashed gray;
border-radius: 8px;
background: lightyellow;
background-size: 100%;
background-repeat: no-repeat;
text-align: center;
}
#dropBox div {
margin: 100px 70px;
color: orange;
font-size: 25px;
font-family: Verdana, Arial, sans-serif;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/file.css" />
<script>
<!-- File processing-->
function procesFiles(files) {
var file = files[0];
var reader = new FileReader();
reader.onload = function(e) {
var output = document.getElementById("fileOutput");
output.textContent = e.target.result;
};
reader.readAsText(file);
}
<!-- File input-->
function showFileInput() {
var fileInput = document.getElementById("fileInput");
fileInput.click();
}
<!-- Drop box -->
var dropBox;
window.onload = function() {
dropBox = document.getElementById("dropBox");
dropBox.ondragenter = ignoreDrag;
dropBox.ondragover = ignoreDrag;
dropBox.ondrop = drop;
}
function ignoreDrag(e) {
e.stopPropagation();
e.preventDefault();
}
function drop(e) {
e.stopPropagation();
e.preventDefault();
var data = e.dataTransfer.files;
var files = data.files;
procesFiles(files);
}
</script>
</head>
<body>
<div id="dropBox">
<div>Drop your file here...</div>
</div>
<input id="fileInput" type="file" onchange="procesFiles(this.files)"/>
<button onclick="showFileInput()">Get new file!</button>
<div id="fileOutput" style="width:500px; height:300px;">
</div>
</body>
</html>
My html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/file.css" />
<script>
<!-- File processing-->
function procesFiles(files) {
var file = files[0];
var reader = new FileReader();
reader.onload = function(e) {
var output = document.getElementById("fileOutput");
output.textContent = e.target.result;
};
reader.readAsText(file);
}
<!-- File input-->
function showFileInput() {
var fileInput = document.getElementById("fileInput");
fileInput.click();
}
<!-- Drop box -->
var dropBox;
window.onload = function() {
dropBox = document.getElementById("dropBox");
dropBox.ondragenter = ignoreDrag;
dropBox.ondragover = ignoreDrag;
dropBox.ondrop = drop;
}
function ignoreDrag(e) {
e.stopPropagation;
e.preventDefault;
}
function drop(e) {
e.stopPropagation;
e.preventDefault;
var data = e.dataTransfer.files;
var files = data.files;
procesFiles(files);
}
</script>
</head>
<body>
<div id="dropBox">
<div>Drop your file here...</div>
</div>
<input id="fileInput" type="file" onchange="procesFiles(this.files)"/>
<button onclick="showFileInput()">Get new file!</button>
<div id="fileOutput" style="width:500px; height:300px;">
</div>
</body>
</html>
And also my css file:
#fileInput {
display: none;
}
#dropBox {
margin: 15px;
width: 300px;
height: 300px;
border: 5px dashed gray;
border-radius: 8px;
background: lightyellow;
background-size: 100%;
background-repeat: no-repeat;
text-align: center;
}
#dropBox div {
margin: 100px 70px;
color: orange;
font-size: 25px;
font-family: Verdana, Arial, sans-serif;
}
Do you have any idea, what could be wrong?
--Edit--
I have one more questin - how can block the from openig the droping file?
e.stopPropagation;
e.preventDefault;
These are supposed to be functions:
e.stopPropagation();
e.preventDefault();

Categories

Resources