-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.js
77 lines (55 loc) · 2.39 KB
/
App.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
//
//created by Finhane Artur
//on Dec/27th/2023
//12:27 PM
//selecting all required elements
const dropArea = document.querySelector(".drag-area"),
dragText = dropArea.querySelector("header"),
button = dropArea.querySelector("button"),
input = dropArea.querySelector("input");
let file; //this variable is global and it will be used inside multiple functions
button.onclick = ()=>{
input.click(); //if user click on the button then the input is also clicked
}
input.addEventListener("change", function(){
//getting user select file and [0] this means if user select multiple files then we'll select only the first one
file = this.files[0];
dropArea.classList.add("active");
showFile(); //calling function
});
//If user Drag File Over DropArea
dropArea.addEventListener("dragover", (event)=>{
event.preventDefault(); //preventing from default behaviour
dropArea.classList.add("active");
dragText.textContent = "Release to Upload File";
});
//If user leave dragged File from DropArea
dropArea.addEventListener("dragleave", ()=>{
dropArea.classList.remove("active");
dragText.textContent = "Drag & Drop to Upload File";
});
//If user drop File on DropArea
dropArea.addEventListener("drop", (event)=>{
event.preventDefault(); //preventing from default behaviour
//getting user select file and [0] this means if user select multiple files then we'll select only the first one
file = event.dataTransfer.files[0];
showFile(); //calling function
});
function showFile(){
let fileType = file.type; //getting selected file type
let validExtensions = ["image/jpeg", "image/jpg", "image/png"]; //adding some valid image extensions in array
if(validExtensions.includes(fileType)){ //if user selected file is an image file
let fileReader = new FileReader(); //creating new FileReader object
fileReader.onload = ()=>{
let fileURL = fileReader.result; //passing user file source in fileURL variable
let imgTag = `<img src="${fileURL}" alt="image">`; //creating an img tag and passing user selected file source inside src
attribute
dropArea.innerHTML = imgTag; //adding that created img tag inside dropArea container
}
fileReader.readAsDataURL(file);
}else{
alert("This is not an Image File!");
dropArea.classList.remove("active");
dragText.textContent = "Drag & Drop to Upload File";
}
}