How to add Image Overlay in JS with FileReader? - javascript

So far i have managed to get 2 Images on my JS. But i can't get the 1 image above the other. I know it usually works on css with "Z" index but since my images are read by the FileReader I added them into my JS.
Question: What do i have to change to get the image on top of the other one on my Code because im pretty sure its almost finished but i simply cannot find the Error...
My JS:
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<div>')).attr('class', 'position-relative')
.attr('width','200px')
.attr('height','200px')
.css('display','inline-block')
.css('position','relative !important')
.appendTo(placeToInsertImagePreview);
$($.parseHTML('<img>')).attr('src', event.target.result)
.attr('width','200px')
.attr('height','200px')
.css('display','inline-block')
.appendTo(placeToInsertImagePreview);
$($.parseHTML('<div>')).attr('class', 'position-absolute')
.appendTo(placeToInsertImagePreview);
$($.parseHTML('<img>')).attr('src', "/x.png")
.attr('height','80px')
.addClass("")
.css('display','inline-block')
.appendTo(placeToInsertImagePreview);
}
reader.readAsDataURL(input.files[i],);
}
}
My HTML:
<div id="form1">
<input value="" type="file" id="images" name="images[]" accept="image/*" multiple />
<div id="previewHolder" data-item-id-div="" multiple="" class="position-relative">
<div class="position-absolute delete-image">
<img class="image-deletepreview" height=80px style="margin-right: 10px;" src="/x.png" />
</div>
</div>
</div>

So i changed my my JS Code into a 1 liner:
reader.onload = function(event) {
$($.parseHTML('<div>')).attr('class', 'position-relative')
.attr('width','200px')
.attr('height','200px')
.css('display','inline-block')
.css('position','relative !important')
.appendTo(placeToInsertImagePreview);
$($.parseHTML('<img>')).attr('src', event.target.result)
.attr('width','200px')
.attr('height','200px')
.css('display','inline-block')
.appendTo(placeToInsertImagePreview);
$($.parseHTML('<div>')).attr('class', 'position-absolute')
.appendTo(placeToInsertImagePreview);
$($.parseHTML('<img>')).attr('src', "/x.png")
.attr('height','80px')
.addClass("")
.css('display','inline-block')
.appendTo(placeToInsertImagePreview);
}
To this:
reader.onload = function(event) {
$('<div class="position-relative" style="height:200px;width: 200px; display: inline-block; position: relative !important;">' +
'<img alt="" src='+event.target.result+' style="height:200px;width: 100%; display: inline-block;">' +
'<div class="position-absolute" style="top: 0;right: 0;">' +
'<img src="/x.png" class="image-deletepreview" style="height: 20px; display: inline-block;"></div></div>')
.appendTo(placeToInsertImagePreview);
}
I just changed the Div to Position 0 and it worked like a Charm.

Related

How to make a first selected image as a thumbnail image from a list of images in jquery?

Here when the user selects the images it gets append inside the ul tag. This all are working fine(There still might be some problems in the code below since I am very beginner in jquery).
Now what I want to change here is, the image which gets selected at first will have a <li class='thumbnail'> by default then other remaining selected images will not have this thumbnail class in the li tag. But the user later on can change the thumbnail image by clicking the image. How can I do it here ?
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
img = `
<li class="thumbnail">
<div class="image">
<img src="${e.target.result}" width="83" height="100"/>
<div class="close"><div class="ic-close" id="img-remove"></div>
</div>
<p>Thumbnail</p></li>
`
$('#blah').append(img);
if ( $('ul#blah li').length > 5 ) {
$("#blah li:last-child").remove();
alert("You can't upload more than 5 images.");
}
}
reader.readAsDataURL(input.files[0]);
$('ul#blah').on('click','.ic-close',function(e) {
console.log('k');
$(this).closest('li').remove();
});
}
}
$("#imgInp").change(function(){
readURL(this);
});
</script>
html
<div class="col-md-6 form-group">
<label for="">Upload Image</label>
<ul class="list list-inline" id="blah">
<div class="files--upload"><input name='image' class="d-none imgUpload" type="file"
id="imgInp" placeholder=""/><label class="upload-label" for="imgInp">
<div class="ic-add"></div>
<div class="mt-2">Add Photo</div>
</label></div>
</ul>
</div>
One of the simplest ways to download previews is with a fast counter, which will prohibit subsequent downloads to the preview.
I have declared globally a variable:
var prew = true;
Here there is a one-time addition of a image for the preview, and also, the prew is assigned a false, which means the impossibility of further adding a image to this div (#img_prew).
if(prew) {
$('#img_prew').append(img);
$('#img_prew').find('.thumbnail .image p').text('This is a preview');
prew = false;
}
Created div for preview:
<div id="img_prew">...</div>
And at the end I set the width and height through css:
#img_prew img{
width: 300px;
height: 300px;
}
var prew = true;
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
img = `
<li class="thumbnail">
<div class="image">
<img src="${e.target.result}" width="83" height="100"/>
<div class="close"><div class="ic-close" id="img-remove"></div>
</div>
<p>Thumbnail</p></li>
`
if(prew) {
$('#img_prew').append(img);
$('#img_prew').find('.thumbnail .image p').text('This is a preview');
prew = false;
}
$('#blah').append(img);
if ( $('ul#blah li').length > 5 ) {
$("#blah li:last-child").remove();
alert("You can't upload more than 5 images.");
}
}
reader.readAsDataURL(input.files[0]);
$('ul#blah').on('click','.ic-close',function(e) {
console.log('k');
$(this).closest('li').remove();
});
}
}
$("#imgInp").change(function(){
readURL(this);
});
#img_prew img{
width: 300px;
height: 300px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.17.0/jquery.validate.js"></script>
<div class="col-md-6 form-group">
<label for="">Upload Image</label>
<div id="img_prew"></div>
<ul class="list list-inline" id="blah">
<div class="files--upload"><input name='image' class="d-none imgUpload" type="file"
id="imgInp" placeholder=""/><label class="upload-label" for="imgInp">
<div class="ic-add"></div>
<div class="mt-2">Add Photo</div>
</label></div>
</ul>
</div>

How do I show image preview though jquery?

I have a field which is upload image images but the problem is this field has add row functionality with the help of append function. What I want to show the image preview on select of the image in each added row so, please tell me how I can do this.
view page-
jQuery(document).ready(function() {
$("#append").click(function(e) {
e.preventDefault();
$(".inc").append('<div class="controls">\
<input name="product_image[]" id="product_image" class="form-control" type="file">\
Remove\<div class="col-sm-10 col-sm-offset-2" style="margin-top: 10px;"><img src="" class="imgpre" id="imgPrev" style="width: 200px; height: 150px; border: 1px solid #ddd" ></div><br>\
<br>\
</div>');
return false;
});
jQuery(document).on('click', '.remove_this', function() {
jQuery(this).parent().remove();
return false;
});
$("input[type=submit]").click(function(e) {
e.preventDefault();
$.map($(".inc :text"), function(el) {
return el.value
}).join(",\n")
})
});
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#imgPrev').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#product_image").change(function() {
readURL(this);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label class="col-sm-2 control-label" for="parentId">Image</label>
<div class="col-sm-6 inc">
<input name="product_image[]" id="product_image" class="form-control" type="file"> <button style="margin-left: 50px; position:relative;left:575px;top:-31px;" class="btn btn-info" type="submit" id="append" name="append">
Add</button>
<br>
<br>
</div>
<div class="col-sm-10 col-sm-offset-2" style="margin-top: 10px;">
<img src="" class="imgPrev" id="imgPrev" style="width: 200px; height: 150px; border: 1px solid #ddd">
</div>
</div>
Starting with your code (but modified, separated CSS etc.) I came up with this quick solution :
$(document).on("change", "input.form-control", function() {
readURL(this);
});
const readURL = input => {
if (input.files && input.files[0]) {
let reader = new FileReader();
reader.onload = e => {
$(input)
.siblings("img")
.attr("src", e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
};
$("#append")
.click(() => {
$(".form-group").append(`
<div class="row">
<input class="form-control" type="file">
<br>
<img src="" class="imgPrev">
<button class="remove">Remove</button>
</div>
`);
})
.trigger("click");
$(document).on("click", "button.remove", function() {
$(this).parent().remove();
return false;
});
.btn-add {
margin-left: 50px;
position: relative;
left: 200px;
}
.row {
margin-bottom: 20px;
}
.row .imgPrev {
width: 200px;
height: 150px;
border: 1px solid #ddd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<button class="btn btn-add" id="append">Add</button>
</div>

JS upload cropper with two instances

I'm trying to upload a second img to the cropper that populates the second .img-result. The cropper should populae whatever was uploaded, and then when the save btn is pressed, the .img-result is updated.
I added the attribute data-up but I'm not sure how to call it in the JS.
// vars
var result = document.querySelector('.result'),
img_result = document.querySelector('.img-result'),
img_w = document.querySelector('.img-w'),
img_h = document.querySelector('.img-h'),
options = document.querySelector('.options'),
save = document.querySelector('.save'),
cropped = document.querySelector('.cropped'),
upload = document.querySelector('.file'),
cropper = '';
// on change show image with crop options
upload.addEventListener('change', function(e) {
if (e.target.files.length) {
// start file reader
var reader = new FileReader();
reader.onload = function(e) {
if (e.target.result) {
// create new image
var img = document.createElement('img');
img.id = 'image';
img.src = e.target.result;
// clean result before
result.innerHTML = '';
// append new image
result.appendChild(img);
// init cropper
cropper = new Cropper(img);
}
};
reader.readAsDataURL(e.target.files[0]);
}
});
// save on click
save.addEventListener('click', function(e) {
e.preventDefault();
// get result to data uri
var imgSrc = cropper.getCroppedCanvas({
width: img_w.value // input value
}).toDataURL();
// show image cropped
cropped.src = imgSrc;
});
.img-result {
border: 2px solid;
width: 50px;
height: 50px;
}
.img-result img {
max-height: 100%;
max-width: 100%;
}
.page {
display: flex;
align-items: flex-start;
flex-wrap: wrap;
height: 100%;
}
.result {
display: flex;
}
.box {
padding: 0.5em;
width: 100%;
margin: 0.5em;
}
.box-2 {
padding: 0.5em;
width: calc(100%/2 - 1em);
}
.img-w {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/0.8.1/cropper.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/cropper/2.3.4/cropper.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main class="page">
<div class="box">
<div class="options">
<input type="number" class="img-w" value="300" min="100" max="1200" />
</div>
<button class="btn save">Save</button>
</div>
<div class="box">
<input class="file" type="file" id="file-input" data-up="1">
</div>
<div class="box">
<input class="file" type="file" id="file-input" data-up="2">
</div>
<div class="box-2">
<div class="result"></div>
</div>
<div class="result">
<div class="box-2 img-result">
<img class="cropped" src="" alt="" data-up="1">
</div>
<div class="box-2 img-result">
<img class="cropped" src="" alt="" data-up="2">
</div>
</div>
</main>
First of all, as I mentioned in comments. Id must be for each element of your DOM. So, you better change id="file-input" to id="file-input1" and so on.
And It looks like you want to get the attribute value data-up when save function called,
You can do that in this way
save.addEventListener('click', function(e) {
e.preventDefault();
// get result to data uri
document.getElementById('file-input1).getAttribute('data-up')
....

How to upload image file from computer and set as div background image using jQuery?

The HTML code for image file input:
<input type="file" autocomplete="off" name="background-image" accept="image/*" />
The destination div block where I want to dynamically set the background image:
<div class="clock"></div>
The jQuery function I'm currently using for setting image file uploaded as div background image:
$(".background>div>input[type=file]").change(function () {
var fileExtension = ['jpeg', 'jpg', 'png', 'gif', 'bmp'];
if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
alert("Only '.jpeg','.jpg', '.png', '.gif', '.bmp' formats are allowed.");
}
else {
$(".clock").css("background-image",'url("' + $(".background>div>input[type=file]").val() + '")');
}
});
The issue is that the background-image is not being set. This may possibly be because when I checked with browser inspector, the file upload is not containing file url.
Note: The background-color of .clock is set to white initially.Also I'd not like to use a server since my intention is to keep it as client side only application.
This may solve your problem
JS FIDDLE
HTML
<input type='file' id='getval' name="background-image" /><br/><br/>
<div id='clock'></div>
CSS
#clock{
background-image:url('');
background-size:cover;
background-position: center;
height: 250px; width: 250px;
border: 1px solid #bbb;
}
PURE JAVASCRIPT
document.getElementById('getval').addEventListener('change', readURL, true);
function readURL(){
var file = document.getElementById("getval").files[0];
var reader = new FileReader();
reader.onloadend = function(){
document.getElementById('clock').style.backgroundImage = "url(" + reader.result + ")";
}
if(file){
reader.readAsDataURL(file);
}else{
}
}
It's small way to do this without using FileReader.
http://jsfiddle.net/PuneetChawla/vqn7r0nj/
HTML
<input type='file' id='getval' name="background-image" onchange="readURL(event)" /><br/><br/>
<div id='clock'></div>
CSS
#clock{
background-image:url('');
background-size:cover;
background-position: center;
height: 250px; width: 250px;
border: 1px solid #bbb;
}
JavaScript
function readURL(event){
var getImagePath = URL.createObjectURL(event.target.files[0]);
$('#clock').css('background-image', 'url(' + getImagePath + ')');
}
Explanation - The URL.createObjectURL() static method creates a DOMString containing an URL representing the object given in parameter.
var loadFile = function(event) {
var output = document.getElementById('output');
output.style.backgroundImage= "url("+URL.createObjectURL(event.target.files[0])+")";
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<input type="file" accept="image/*" onchange="loadFile(event)">
<div style="width: 500px;height: 500px;" id="output"></div>
</body>
</html>

Issue uploading multiple images to a page with "upload" button...

I have a Fiddle here...
I've accomplished the ability to get an image to load below the upload button, however, how can I upload multiple images to the same page? There are three places where I've allowed the user to upload a specific image.
<div class="element-file" title="Do you want to add an image to the Accreditation Text?">
<label class="title" style="font-weight: bold;">Add an image to the left of the Accreditation text<br>(Image will be resized to 100px by 100px)</label>
<label class="medium" >
<input type='file' onchange="readURL(this);" />
</label>
<p><strong>(Image will display below)</strong></p>
<div style="max-width: 100px; height: auto; border:1px dashed black;">
<img id="accred_image" src="accred" alt="" />
</div>
</div>
And add an image to this area...
<div class="element-file" title="Do you want to add an image to the Accreditation Text?">
<label class="title" style="font-weight: bold;">Would you like to add a logo image?</label>
<label class="medium" >
<input type='file' onchange="readURL(this);" />
</label>
<p><strong>(Image will display below)</strong></p>
<div style="max-width: 140px; height: auto; border:1px dashed black;">
<img id="blah" src="" alt="" />
</div>
</div>
This is my javascript, but when I upload an image, it places the same image in both spots. I thought this had something to do with the class I am uploading from, but creating the new class, doesn't seem to help at all.
$("input").change(function(e) {
for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {
var file = e.originalEvent.srcElement.files[i];
var reader = new FileReader();
reader.onloadend = function() {
$('#accred_image').attr('src', reader.result);
}
reader.readAsDataURL(file); }
});
You need to find that is the img to update.
Try this:
$("input").change(function(e) {
var elemIMG = $(this).parent().parent().find('img'); // find the img to update
for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {
var file = e.originalEvent.srcElement.files[i];
var reader = new FileReader();
reader.onloadend = function() {
elemIMG.attr('src',reader.result); // update the img src
}
reader.readAsDataURL(file); }
});

Categories

Resources