HTML5 drag&drop ignore drop and opens file - javascript

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();

Related

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

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 :)

Dynamically setting background image on Grid cell with JS

The program I am creating is a meme generator. I have a div container set up with display:grid with a few tags inside of that which act as the top and bottom text for the meme. I'm trying to dynamically set the background image for the grid cell using plain vanilla JS. When I attach the link inside the CSS file it works perfectly, but using JS the background-image is never set when i check inside the browser. I put a big arrow so you can see where I am attempting to set the image
const imageLink = document.querySelector('#imageLink');
const topText = document.querySelector('#topText');
const bottomText = document.querySelector('#bottomText');
const memeDiv = document.querySelector('#meme');
//listener for submit
document.addEventListener("submit", function(e) {
e.preventDefault();
//if the user doesn't enter an image, or if they don't enter any text, don't generate the meme when they submit.
if (imageLink.value === "") {
return;
} else if (topText === "" && bottomText === "") {
return;
}
console.log(imageLink.value);
//create elements
var div = document.createElement("div");
//set attribute for div containing our memes
div.setAttribute("id", "meme");
//When the page loads apply the users photo to the background of the grid
window.addEventListener('DOMContentLoaded', function() {
memeDiv.style.backgroundImage = `url(${imageLink.value})`; // < -- -- -
});
//create text and remove button for the memes
const top = document.createElement("p"); //for top text
const bottom = document.createElement("p"); //for bottom text
const removeBtn = document.createElement("input");
//remove button attributes
removeBtn.setAttribute("id", "remove");
removeBtn.setAttribute("type", "image");
removeBtn.setAttribute("height", "200px");
removeBtn.setAttribute("width", "200px");
removeBtn.setAttribute(
"src",
"https://www.freeiconspng.com/uploads/x-png-33.png"
);
//set attributes for text
top.setAttribute("id", "top");
top.innerText = topText.value;
bottom.setAttribute("id", "bottom");
bottom.innerText = bottomText.value;
//put the top and bottom text with the remove button together with the same div
div.appendChild(top);
div.appendChild(bottom);
div.appendChild(removeBtn);
//append to the div
document.querySelector("#memeContainer").appendChild(div);
//reset
imageLink.value = "";
topText.value = "";
bottomText.value = "";
})
document.addEventListener("click", function(e) {
if (e.target.id === "remove") {
e.target.parentElement.remove();
} else {
return;
}
})
* {
margin: 0px;
}
#formContainer {
background-color: blue;
margin-bottom: 5px;
text-align: center;
}
h1 {
text-align: center;
background-color: blue;
margin: 0px;
}
#memeContainer {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(3, 300px);
grid-gap: 5px;
}
#top,
#bottom,
#remove {
position: relative;
display: inline;
}
#top {
left: 225px;
z-index: 1;
font-family: Impact;
font-size: 40px;
/* color:white; */
}
#bottom {
top: 300px;
left: 225px;
z-index: 2;
font-family: Impact;
font-size: 40px;
/* color:white; */
}
#remove {
top: -150px;
left: 180px;
z-index: 3;
/* filter: opacity(1%); */
}
#remove:hover {
z-index: 3;
filter: opacity(25%);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Meme Generator</title>
<link rel="stylesheet" href="app.css">
</head>
<body>
<h1>MEME GENERATOR</h1>
<div id="formContainer">
<form>
<input id="imageLink" type="text" placeholder="please link to an image">
<input id="topText" type="text" placeholder="TOP TEXT">
<input id="bottomText" type="text" placeholder="BOTTOM TEXT">
<button type="submit">submit</button>
</form>
</div>
<div id="memeContainer"></div>
<script src="app.js"></script>
</body>
</html>
The DOMContentLoaded event is only called once whenever all HTML have been loaded. So you are only adding an event listener which never fires and thus nothing happens.
window.addEventListener('DOMContentLoaded', function() {
memeDiv.style.backgroundImage = `url(${imageLink.value})`;
});
Remove the event listener and correct the memeDiv variable name to div and your code will run.
div.style.backgroundImage = `url(${imageLink.value})`;
const imageLink = document.querySelector('#imageLink');
const topText = document.querySelector('#topText');
const bottomText = document.querySelector('#bottomText');
const memeDiv = document.querySelector('#meme');
//listener for submit
document.addEventListener("submit", function(e) {
e.preventDefault();
//if the user doesn't enter an image, or if they don't enter any text, don't generate the meme when they submit.
if (imageLink.value === "") {
return;
} else if (topText.value === "" && bottomText.value === "") {
return;
}
console.log(imageLink.value);
//create elements
var div = document.createElement("div");
//set attribute for div containing our memes
div.setAttribute("id", "meme");
//When the page loads apply the users photo to the background of the grid
div.style.backgroundImage = `url(${imageLink.value})`; // < -- -- -
//create text and remove button for the memes
const top = document.createElement("p"); //for top text
const bottom = document.createElement("p"); //for bottom text
const removeBtn = document.createElement("input");
//remove button attributes
removeBtn.setAttribute("id", "remove");
removeBtn.setAttribute("type", "image");
removeBtn.setAttribute("height", "200px");
removeBtn.setAttribute("width", "200px");
removeBtn.setAttribute(
"src",
"https://www.freeiconspng.com/uploads/x-png-33.png"
);
//set attributes for text
top.setAttribute("id", "top");
top.innerText = topText.value;
bottom.setAttribute("id", "bottom");
bottom.innerText = bottomText.value;
//put the top and bottom text with the remove button together with the same div
div.appendChild(top);
div.appendChild(bottom);
div.appendChild(removeBtn);
//append to the div
document.querySelector("#memeContainer").appendChild(div);
//reset
imageLink.value = "";
topText.value = "";
bottomText.value = "";
})
document.addEventListener("click", function(e) {
if (e.target.id === "remove") {
e.target.parentElement.remove();
} else {
return;
}
})
* {
margin: 0px;
}
#formContainer {
background-color: blue;
margin-bottom: 5px;
text-align: center;
}
h1 {
text-align: center;
background-color: blue;
margin: 0px;
}
#memeContainer {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(3, 300px);
grid-gap: 5px;
}
#top,
#bottom,
#remove {
position: relative;
display: inline;
}
#top {
left: 225px;
z-index: 1;
font-family: Impact;
font-size: 40px;
/* color:white; */
}
#bottom {
top: 300px;
left: 225px;
z-index: 2;
font-family: Impact;
font-size: 40px;
/* color:white; */
}
#remove {
top: -150px;
left: 180px;
z-index: 3;
/* filter: opacity(1%); */
}
#remove:hover {
z-index: 3;
filter: opacity(25%);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Meme Generator</title>
<link rel="stylesheet" href="app.css">
</head>
<body>
<h1>MEME GENERATOR</h1>
<div id="formContainer">
<form>
<input id="imageLink" type="text" placeholder="please link to an image">
<input id="topText" type="text" placeholder="TOP TEXT">
<input id="bottomText" type="text" placeholder="BOTTOM TEXT">
<button type="submit">submit</button>
</form>
</div>
<div id="memeContainer"></div>
<script src="app.js"></script>
</body>
</html>

I want to save textbox to .txt file in HTML using JavaScript but I have an error

I have a fake web site for a school project and I want to get the HTML code to send the information from textbox to .txt file with Javascript, but it doesn't work and I don't know why. Can you tell me where the error is, please?
<section>
<form method:"POST">
<label>Escrigui el seu usuari:</label>
<input type="text" name="usuari" id="usuari" size="20"/>
<label>Escrigui la seva contrasenya:</label>
<input type="text" name="contrasenya" id="contrasenya" size="20"/>
<input type="button" value="submit" id="button" href="" onclick="WriteToFile()"/>
</form>
<script type="text/javascript">
function WriteToFile(passForm){
set fso = CreateObject("Scripting.FileSystemObject");
set s = fso.CreateTextFile("filename.txt", True);
var usuari = document.getElementById("usuari").value;
var contrasenya = document.getElementById("contrasenya").value;
s.writeline("usuari :" + usuari);
s.writeline("contrasenya :" + contrasenya);
s.writeline("-----------------------------");
s.Close();
}
</script>
I've programmed a "Notebook" that exports the input to a txt file which is ready to be downloaded after:
<html><head>
<style>
body {
margin: 0%;
}
#font-face {
font-family: "CG";
src: url(./resources/CENTURYGOTHIC.ttf) format("truetype");
}
textarea {
margin-left: 0%;
margin-top: 0%;
height: 80%;
width: 100%;
resize: none;
visibility: visible;
background-color: white;
border-color: black;
}
button {
background-color: white;
font-family: CG;
border-color: black;
border-width: 1px;
padding-top: 10px;
padding-bottom: 10px;
padding-right: 20px;
padding-left: 20px;
margin-top: 10px;
text-transform: capitalize;
}
</style></head>
<body>
<textarea id="textbox" placeholder="You can write anything here... just start tyipng what you would like to remember: Notes, Homework, Tests, just anything."></textarea>
<button id="create">SAVE TO FILE</button>
<a download="notes.txt" id="downloadlink" style="display: none"><button onclick="functionreset()">DOWNLOAD</button></a>
<br>
<script>
(function() {
var textFile = null,
makeTextFile = function(text) {
var data = new Blob([text], {
type: 'text/plain'
});
// If we are replacing a previously generated file we need to
// manually revoke the object URL to avoid memory leaks.
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
return textFile;
};
var create = document.getElementById('create'),
textbox = document.getElementById('textbox');
create.addEventListener('click', function() {
var link = document.getElementById('downloadlink');
link.href = makeTextFile(textbox.value);
link.style.display = 'block';
document.getElementById('create').style.display = 'none';
}, false);
})();
function functionreset() {
var link = document.getElementById('downloadlink');
link.style.display = 'none';
document.getElementById('create').style.display = 'block';
}
</script>
<script>
document.getElementById("textbox").onchange = function() {functionreset()}
</script>
<!-- <iframe height=100% width=100%; src=./test.html></iframe>-->
</body></html>
maybe you can use fragments of this...
Notify me if it worked😉

How to remove selected image from preview and as well as from url variable before uploading it

I have the code for the image preview but after removing it only goes from preview but not from url variable and the removed images url are also being stored in database.
I'm using Spring Boot for controllers.
how to remove the image while clicking the remove button and also uploaded link from the uploaded files list
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(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();
});
});
fileReader.readAsDataURL(f);
}
});
} else {
alert("Your browser doesn't support to File API")
}
});
</script>
<style>
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;
}
</style>
</head>
<body>
<div class="field" align="left">
<h3>Upload your images</h3>
<input type="file" id="files" multiple="multiple" />
</div>
</body>
</html>
Please help how to remove the image from preview and also from pojo variable that being saved to database.
Do empty input file field as well
$(".remove").click(function(){
$(this).parent(".pip").remove();
$("#files").val(null);
});`

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()

Categories

Resources