dna.js ~~ Photo upload component
An uncomplicated user interface library
by pilafmon
HTML
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/dna.css">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/dna.min.js"></script>
<h1>Photo Upload</h1>
<div data-component=photo-upload>
<button data-click=photoUpload.open>Upload Image</button>
<input type=file accept=image/* data-change=photoUpload.process>
<figure><img src=# alt=avatar></figure>
</div>
<div data-component=photo-upload>
<button data-click=photoUpload.open>Upload Image</button>
<input type=file accept=image/* data-change=photoUpload.process>
<figure><img src=# alt=avatar></figure>
</div>
CSS
body {
font-family: system-ui, sans-serif;
margin: 30px;
}
button:hover {
cursor: pointer;
}
/* Photo Upload Component */
[data-component=photo-upload] {
display: flex;
justify-content: space-between;
align-items: start;
background-color: goldenrod;
padding: 10px 20px;
margin-bottom: 20px;
}
[data-component=photo-upload] input {
display: none;
}
[data-component=photo-upload] figure {
display: none;
margin: 0px;
}
[data-component=photo-upload] figure img {
max-height: 120px;
border: 8px solid silver;
}
JavaScript
// dnajs.org
const photoUpload = {
open: (elem, event, component) => {
component.find('input[type=file]').click();
},
process: (elem, event, component) => {
const file = elem[0].files[0];
const reader = new FileReader();
const insertImage = (loadEvent) => {
const imgSrc = { src: loadEvent.target.result };
component.find('figure').hide().fadeIn()
.find('img').attr(imgSrc);
console.log(event.target.result); //see js console
};
reader.onload = insertImage;
reader.readAsDataURL(file);
},
};