How to prevent this Multiple drag and drop image file from duplicate - javascript

I have here 3 div from my drag and drop image file, the file names are array and i calling it using the class then i loop it. My problem is when i try to put image file in specific div, one of those 3 div, it duplicates the image to all of the remaining div. How do i prevent this and allow me to put image only in my chosen div?
Here is my code https://jsfiddle.net/qm9nkco7/2/
Html
<div class="sideBar_paddIT">
<input type="file" name="file_name[]" class="file_class" id="file_id0">
<div class="drag_here">
<div class="drag_me" id="drag_me_id">
<img class="img_here" src="" width="100%" >
<center class="center_html">
Click or Drag image here
</center>
</div>
</div>
</div>
<div class="sideBar_paddIT">
<input type="file" name="file_name[]" class="file_class" id="file_id0">
<div class="drag_here">
<div class="drag_me" id="drag_me_id">
<img class="img_here" src="" width="100%" >
<center class="center_html">
Click or Drag image here
</center>
</div>
</div>
</div>
<div class="sideBar_paddIT">
<input type="file" name="file_name[]" class="file_class" id="file_id0">
<div class="drag_here">
<div class="drag_me" id="drag_me_id">
<img class="img_here" src="" width="100%" >
<center class="center_html">
Click or Drag image here
</center>
</div>
</div>
</div>
JS
$(document).on('click','.drag_me', function(){
$('.file_class').trigger('click');
});
var imageLoader = document.getElementsByName('file_name[]');
for(var i= 0; i < imageLoader.length; i++){
imageLoader[i].addEventListener('change', handleImage, false);
}
function handleImage(e) {
e.stopPropagation();
e.preventDefault();
if(e.target.files.length === 0){
return false;
}
var reader = new FileReader();
reader.onload = function (event) {
$('.drag_me .img_here').attr('src',event.target.result);
}
var taste_it = e.target.files[0];
var file_name = taste_it.name;
var file_size = taste_it.size;
var file_type = taste_it.type;
if(!check(file_type)){
$('.trigger_danger_alert_changable').show().delay(5000).fadeOut();
$('#palitan_ng_text').html('Invalid file format');
return false;
}
if(file_size > 1500000){
$('.trigger_danger_alert_changable').show().delay(5000).fadeOut();
$('#palitan_ng_text').html('File size too large');
$('.file_class').val(''); // <-- kaya d nag aalert dahil may laman,
return false;
}else{
reader.readAsDataURL(e.target.files[0]);
$('.center_html').hide();
$('.image_name').html(file_name).css({'font-size' : '14px', 'color' : 'black'});
}
}
var obj = $('.drag_me');
obj.on('dragover', function(e){
e.stopPropagation();
e.preventDefault();
$(this).css('border', '2px solid #39ADCD');
});
obj.on('drop', function(e){
e.stopPropagation();
e.preventDefault();
$(this).css('border', '2px dotted #39ADCD');
var files = e.originalEvent.dataTransfer.files;
var file = files[0];
var file_name = file.name;
var file_size = file.size;
var file_type = file.type;
if(!check(file_type)){
$('.trigger_danger_alert_changable').show().delay(5000).fadeOut();
$('#palitan_ng_text').html('Ivalid file format');
return false;
}
if(file_size > 1500000){
$('.trigger_danger_alert_changable').show().delay(5000).fadeOut();
$('#palitan_ng_text').html('File size too large');
return false;
}else{
for(var i = 0; i<imageLoader.length; i++){
imageLoader[i].files = files;
}
$('.center_html').html(file_name).css({'font-size' : '14px', 'color' : 'black'});
}
});
function check(image){
switch(image){
case 'image/jpeg':
return 1;
case 'image/jpg':
return 1;
case 'image/png':
return 1;
case 'image/gif':
return 1;
default:
return 0;
}
}
Anyone can help me

Don't use identical ids for multiple elements
The <center> tag is deprecated. Use style="text-align: center;", preferably in a class.
Now onto your actual problem, which comprises of two parts:
$('.drag_me .img_here').attr('src', event.target.result);
This line assigns event.target.result to the src attribute of every .drag_me .img_here element.
$(document).on('click','.drag_me', function(){
$('.file_class').trigger('click');
});
This causes a click on any .drag_me element to trigger clicks on every .file_class element.
Both of these issues can be solved by not using identical ids for different elements, then referencing those ids to specify an individual element to target:
HTML: Notice the new ids of the .drag_me and .file_class elements
<div class="sideBar_paddIT">
<input type="file" name="file_name[]" class="file_class" id="file_id_0">
<div class="drag_here">
<div class="drag_me" id="drag_me_id_0">
<img class="img_here" src="" width="100%">
<center class="center_html">
Click or Drag image here
</center>
</div>
</div>
</div>
<div class="sideBar_paddIT">
<input type="file" name="file_name[]" class="file_class" id="file_id_1">
<div class="drag_here">
<div class="drag_me" id="drag_me_id_1">
<img class="img_here" src="" width="100%">
<center class="center_html">
Click or Drag image here
</center>
</div>
</div>
</div>
<div class="sideBar_paddIT">
<input type="file" name="file_name[]" class="file_class" id="file_id_2">
<div class="drag_here">
<div class="drag_me" id="drag_me_id_2">
<img class="img_here" src="" width="100%">
<center class="center_html">
Click or Drag image here
</center>
</div>
</div>
</div>
JavaScript: See the comments /**** ... ****/
$(document).on('click', '.drag_me', function(ev) {
/**** Get the specific element using the number in the id attribute ****/
var idNum = $(this).attr('id').split('_')[3];
$('.file_class').eq(idNum).trigger('click');
});
var imageLoader = document.getElementsByName('file_name[]');
for (var i = 0; i < imageLoader.length; i++) {
imageLoader[i].addEventListener('change', handleImage, false);
}
function handleImage(e) {
e.stopPropagation();
e.preventDefault();
/**** Get the current input field by using the number in the id attribute ****/
var currentInput = e.target.id.split('_')[2];
if (e.target.files.length === 0) {
return false;
}
var reader = new FileReader();
reader.onload = function(event) {
/**** Use the current input field instead of all the input fields ****/
$('#drag_me_id_' + currentInput + ' .img_here').attr('src', event.target.result);
}
var taste_it = e.target.files[0];
var file_name = taste_it.name;
var file_size = taste_it.size;
var file_type = taste_it.type;
if (!check(file_type)) {
$('.trigger_danger_alert_changable').show().delay(5000).fadeOut();
$('#palitan_ng_text').html('Invalid file format');
return false;
}
if (file_size > 1500000) {
$('.trigger_danger_alert_changable').show().delay(5000).fadeOut();
$('#palitan_ng_text').html('File size too large');
$('.file_class').val(''); // <-- kaya d nag aalert dahil may laman,
return false;
} else {
reader.readAsDataURL(e.target.files[0]);
$('.center_html').hide();
$('.image_name').html(file_name).css({
'font-size': '14px',
'color': 'black'
});
}
}
/** Rest of the code is unchanged **/
See New Fiddle Here

Related

Random image from html on button click

I am trying to make a script that will take the images from one div element and put it to div rndmImage randomly on button click, I should see images when document is loaded, but the new div where images should go after click must be empty until click heapends. And I need only JavaScript, no jQuery, alse i can not change the html, and it has to work for any number of images. So if you have some ideas that would be great. Here's my code.
window.addEventListener('load', start, false);
function start() {
var butt = document.getElementsByTagName('button')[0];
var rnImg = document.getElementsByClassName('ekran');
var pictures = document.getElementsByTagName('img');
var choose = Math.floor(Math.random()*pictures.length);
butt.addEventListener('click', menjaj, false);
function menjaj(e) {
var new = e.button;
var img = [];
for(var i = 0; i< pictures.length; i++) {
var dodaj = img[i];
img.push(dodaj);
}
//ekran.src = 'slike/' + slike[izbor] + '.jpg';
}
}
<body>
<div class="wrapper">
<div>
<img src="slike/leto1.jpg" alt="leto1">
<img src="slike/leto2.jpg" alt="leto2">
<img src="slike/leto3.jpg" alt="leto3">
<img src="slike/leto4.jpg" alt="leto4">
<img src="slike/leto5.jpg" alt="leto5">
<img src="slike/leto6.jpg" alt="leto6">
<img src="slike/leto7.jpg" alt="leto7">
<img src="slike/leto8.jpg" alt="leto8">
<img src="slike/leto9.jpg" alt="leto9">
</div>
<div>
<button type="button">choose</button>
</div>
<div class="rndmImage"></div>
</div>
</body>
This is a working snippet of your code:
window.addEventListener('load', start, false);
function start () {
var butt = document.getElementsByTagName('button')[0];
var rnImg = document.getElementsByClassName('rndmImage')[0]; //Change selector to existing class and select the first (the only) one
var pictures = document.getElementsByTagName('img');
butt.addEventListener('click', menjaj, false);
function menjaj (e) {
// var new = e.button;// 'new' is reserved word in JS, you can't use it as variable name
// var btn = e.button;// but this line is useless
var choose = Math.floor(Math.random() * pictures.length); //better move this line inside this function to get rundom image every button clicks
var img = document.createElement('img'); //creates new img tag
img.src = pictures[choose].src;
rnImg.innerHTML = ''; //to delete previous image
rnImg.appendChild(img);
// var img = []; //useless lines of code
// for(var i = 0; i< pictures.length; i++) {
// var dodaj = img[i];
// img.push(dodaj);
// }
//ekran.src = 'slike/' + slike[izbor] + '.jpg';
}
}
welcome to StackOverflow!
I would first hide the .wrapper > div img as that will prevent the images to show, then, append a data-pos to help select the position and simply randomize them and pick the src to show on the placeholder
and remember that you have a <div> as placeholder, so you can't assign src, only if you change it to <img>
so, something like this 😊
function chooseImg() {
// get total images available
var totalImages = document.querySelectorAll('.wrapper > div img').length
log('totalImages', totalImages)
// get a random position
var rndPosition = Math.floor(Math.random() * totalImages)
log('rndPosition', rndPosition)
// get hold of the image for such position
var rndImage = document.querySelector('.wrapper > div img[data-pos="' + rndPosition + '"]')
log('rndImage', rndImage)
// assign the source to the DIV
document.querySelector('.rndmImage').style = 'background-image: url("' + rndImage.src + '")'
}
function log(txt, obj) {
console.log(txt, obj)
}
.wrapper > div img {
display: none;
}
.rndmImage {
background-size: contain;
background-repeat: no-repeat;
width: 100px;
height: 100px;
}
<div class="wrapper">
<div>
<img data-pos="0" src="https://randomwordgenerator.com/img/picture-generator/54e5d2434953a514f1dc8460962e33791c3ad6e04e507440742f7cd09645cc_640.jpg" alt="leto1">
<img data-pos="1" src="https://randomwordgenerator.com/img/picture-generator/54e2d1404a57a814f1dc8460962e33791c3ad6e04e5074417c2d78d19f44c4_640.jpg" alt="leto2">
<img data-pos="2" src="https://randomwordgenerator.com/img/picture-generator/57e2d5444851a414f1dc8460962e33791c3ad6e04e50744172287ad2914fc4_640.jpg" alt="leto3">
<img data-pos="3" src="https://randomwordgenerator.com/img/picture-generator/51e8d0444f56b10ff3d8992cc12c30771037dbf85254794e722c73d19245_640.jpg" alt="leto4">
<img data-pos="4" src="https://randomwordgenerator.com/img/picture-generator/53e4d2464a56a914f1dc8460962e33791c3ad6e04e507440722d7cd39345c1_640.jpg" alt="leto5">
<img data-pos="5" src="https://randomwordgenerator.com/img/picture-generator/57e9dc434b5ba414f1dc8460962e33791c3ad6e04e50744172297bd5934cc4_640.jpg" alt="leto6">
<img data-pos="6" src="https://randomwordgenerator.com/img/picture-generator/55e1dc4b4254ad14f1dc8460962e33791c3ad6e04e507440722d72d09249c7_640.jpg" alt="leto7">
<img data-pos="7" src="https://randomwordgenerator.com/img/picture-generator/57e9d4474e54a814f1dc8460962e33791c3ad6e04e50744172297cdd974cc0_640.jpg" alt="leto8">
<img data-pos="8" src="https://randomwordgenerator.com/img/picture-generator/53e6dc404951b10ff3d8992cc12c30771037dbf852547848702e7ed19348_640.jpg" alt="leto9">
</div>
<div>
<button type="button" onclick="chooseImg()">choose</button>
</div>
<div class="rndmImage"></div>
</div>
<div class="wrapper">
<img src="../Assets1/Image/1.svg" alt="" />
<img src="../Assets1/Image/2.svg" alt="" />
<img src="../Assets1/Image/3.svg" alt="" />
</div>
<button>Click</button>
<div class="randomImageContainer"></div>
const button = document.querySelector('button');
button.addEventListener('click', randomImage);
function randomImage() {
const image = document.querySelectorAll('.wrapper > img');
const randomImageContainer = document.querySelector('.randomImageContainer');
let randomNumber = Math.floor(Math.random() * image.length);
const img = document.createElement('img');
img.src = image[randomNumber].src;
randomImageContainer.appendChild(img);
}
You can do this with plain javascript like this:
document.querySelector("button").addEventListener("click", () => {
var imgElements = document.querySelectorAll(".wrapper img");
document.querySelector(".rndmImage").innerHTML = imgElements[Math.floor(Math.random() * imgElements.length)].outerHTML;
});
<div class="wrapper">
<div>
<img src="slike/leto1.jpg" alt="leto1">
<img src="slike/leto2.jpg" alt="leto2">
<img src="slike/leto3.jpg" alt="leto3">
<img src="slike/leto4.jpg" alt="leto4">
<img src="slike/leto5.jpg" alt="leto5">
<img src="slike/leto6.jpg" alt="leto6">
<img src="slike/leto7.jpg" alt="leto7">
<img src="slike/leto8.jpg" alt="leto8">
<img src="slike/leto9.jpg" alt="leto9">
</div>
<div>
<button type="button">choose</button>
</div>
<div class="rndmImage"></div>
</div>
If you're able to use randojs, you can even simplify the randomness and make it all cryptographically secure like this:
document.querySelector("button").addEventListener("click", () => document.querySelector(".rndmImage").innerHTML = rando(document.querySelectorAll(".wrapper img")).value.outerHTML);
<script src="https://randojs.com/2.0.0.js"></script>
<div class="wrapper">
<div>
<img src="slike/leto1.jpg" alt="leto1">
<img src="slike/leto2.jpg" alt="leto2">
<img src="slike/leto3.jpg" alt="leto3">
<img src="slike/leto4.jpg" alt="leto4">
<img src="slike/leto5.jpg" alt="leto5">
<img src="slike/leto6.jpg" alt="leto6">
<img src="slike/leto7.jpg" alt="leto7">
<img src="slike/leto8.jpg" alt="leto8">
<img src="slike/leto9.jpg" alt="leto9">
</div>
<div>
<button type="button">choose</button>
</div>
<div class="rndmImage"></div>
</div>
Try this:
this is my image in HTML file
<snap id="image" class="btn btn-warning" onclick="changeImage()">Image</snap>
<image id="imagechange" src="https://picsum.photos/200/300" ></image>
my javascript file
imgcount = 0;
function changeImage() {
document.getElementById("imagechange").src =
"https://picsum.photos/200/" + (300 + imgcount);
imgcount++;
}
everytime you click button you get a new image

jquery preview image not working

So I'm trying to implement a preview button so that when my users clicks on the upload button image they could have a preview but the thing is that it is not working, I wonder why ?? A brief description : I have a js function that creates new elements and append it to a p tag date. It is in this function that is going to create the preview image code
// code for creating new elements
function createElements(){
const userQuestions = document.querySelector('#userQuestions');
userQuestions.insertAdjacentHTML(
'beforeend', '<div class="uploader" onclick="$(\'#filePhoto\').click()"><p id="bg-text">No image</p></div><input type="file" name="userprofile_picture" id="filePhoto" style="display:block;width:185px;" /></center><div class="grid-container">'
);
}
///Code to preview image
function handleImage(e) {
var imageLoader = document.getElementById('filePhoto');
imageLoader.addEventListener('change', handleImage, false);
var reader = new FileReader();
reader.onload = function (event) {
$('.uploader').html( '<img width="300px" height="350px" src="'+event.target.result+'"/>' );
}
reader.readAsDataURL(e.target.files[0]);
}
.uploader {width:50%;height:35%;background:#f3f3f3;border:2px dashed #0091ea;}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="userQuestions"></div>
<button type="button" onclick="createElements()">add elements</button>
</body>
</html>
If you run the snippet above you can see that the button is woeking but the preview is not showing. Could someone help me?
HTML:
<div class="row">
<div class="col-xs-4">
<div class="form-group">
<label>Company Logo</label>
<input type="file" class="form-control" value="" name="companyLogo" id="companyLogo" accept="image/*" />
</div>
</div>
<div id="displayImage">
<img id="imgData" src="#" alt="your image" height="150px" width="150px" />
</div>
</div>
JavaScript:
$("#companyLogo").change(function(e) {
if(e.target.value === "") {
$("#displayImage").hide();
} else {
$("#displayImage").show();
}
readURL(this);
});
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$("#imgData").attr("src", e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
Short n simple
No need to create an element on click.
Just add an image tag and set a default image like no image selected or something like that.
The following code will help you
<input type="file" name="myCutomfile" id="myCutomfile"/>
<img id="customTargetImg" src="default.jpg" width="400" height="250">
$("#myCutomfile").change(function() {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#customTargetImg').attr('src', e.target.result);
}
reader.readAsDataURL(this.files[0]);
}
});
Take advantage of jQuery -- particularly using
event handlers
delegated event handlers for dynamically-created elements
tree traversal methods.
$(function() {
var userQuestions = $('#userQuestions');
// create onclick event handler for your button
$('#addElements').click(function() {
// IDs must be unique - since you can have an arbitrary number of filePhoto, use a class instead
userQuestions.append(
'<div class="uploader"><p id="bg-text">No image</p></div><input type="file" name="userprofile_picture" class="filePhoto" /><div class="grid-container"></div>'
);
});
// create delegated onclick event handler for your .uploader
userQuestions.on('click', '.uploader', function() {
// you only want to target the file input immediately after it
$(this).next('[type=file]').click();
});
// create delegated onchange event handler for your .filePhoto
userQuestions.on('change', '.filePhoto', function() {
// find related uploader
var uploader = $(this).prev('.uploader');
// check file was given
if (this.files && this.files.length) {
var reader = new FileReader();
reader.onload = function(event) {
uploader.html('<img width="300px" height="350px" src="' + event.target.result + '"/>');
}
reader.readAsDataURL(this.files[0]);
}
});
});
.uploader {
width: 50%;
height: 35%;
background: #f3f3f3;
border: 2px dashed #0091ea;
}
.filePhoto {
display: block;
width: 185px;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="userQuestions"></div>
<!-- added ID attribute -->
<button type="button" id="addElements">add elements</button>
</body>
</html>
Edit
This answer is a non-jQuery solution based off your comment.
// code for creating new elements
function createElements() {
// no need to document.querySelector if the selector is an ID
const userQuestions = document.getElementById('userQuestions');
// you want to use onclick/onchange attributes here as they are dynamically created
userQuestions.insertAdjacentHTML(
'beforeend', '<div class="uploader" onclick="selectFile(this)"><p id="bg-text">No image</p></div><input type="file" name="userprofile_picture" onchange="handleImage(this)" />'
);
}
// trigger click on file input that follows the uploader
function selectFile(uploader) {
uploader.nextSibling.click();
}
///Code to preview image
function handleImage(input) {
if (input.files.length) {
var reader = new FileReader();
reader.onload = function(e) {
input.previousSibling.innerHTML =
'<img width="300px" height="350px" src="' + e.target.result + '"/>';
}
reader.readAsDataURL(input.files[0]);
}
}
.uploader {
width: 50%;
height: 35%;
background: #f3f3f3;
border: 2px dashed #0091ea;
}
.filePhoto {
display: block;
width: 185px;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="userQuestions"></div>
<button type="button" onclick="createElements()">add elements</button>
</body>
</html>

How to display multiple thumbnails while uploading images in html using javascript?

function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#documentUpload')
.attr('src', e.target.result)
};
reader.readAsDataURL(input.files[0]);
}
}
<html>
<head></head>
<body>
<ul>
<li>
<input type='file' onchange="readURL(this);" />
<img id="documentUpload" src="#" alt="first image" />
</li>
<li>
<input type='file' onchange="readURL(this);" />
<img id="documentUpload" src="#" alt="second image" />
</li>
</ul>
</body>
</html>
> Blockquote
" In example , click on any choose image button but image will be displayed in first case only . I changed the id in both case and in javascript as well but it didnt work.
code above is solution to how to display image in html "
The problem is ID require be unique. In this example, I add an attribute called document-up, and it works. It's possible in this case select more than one element using attributes or classes.
function readURL(input,option) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
if (option == 1){
$("#documentUpload1")
.attr('src', e.target.result)
} else {
$("#documentUpload2")
.attr('src', e.target.result)
}
};
reader.readAsDataURL(input.files[0]);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html>
<head></head>
<body>
<ul>
<li>
<input id="input1" type='file' onchange="readURL(this,1);" />
<img id="documentUpload1" document-up src="#" alt="first image" />
</li>
<li>
<input id="input2" type='file' onchange="readURL(this,2);" />
<img id="documentUpload2" document-up src="#" alt="second image" />
</li>
</ul>
</body>
</html>
Here's an approach that will work for an arbitrary number of images and an arbitrary number of images per file-picker.
All you need to is wrap the #previewHolder div with a form and handle its submission.
function newEl(tag){return document.createElement(tag)}
function byId(id){return document.getElementById(id)}
function allByTag(tag,parent){return (parent == undefined ? document : parent).getElementsByTagName(tag)}
// useful for HtmlCollection, NodeList, String types
function forEach(array, callback, scope){for (var i=0,n=array.length; i<n; i++)callback.call(scope, array[i], i, array);} // passes back stuff we need
// callback gets data via the .target.result field of the param passed to it.
function loadFileObject(fileObj, loadedCallback){var a = new FileReader();a.onload = loadedCallback;a.readAsDataURL( fileObj );}
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded(evt)
{
byId('addBtn').addEventListener('click', onAddBtnClicked, false);
}
/* html below function needs to create - we dont bother with the img here, since we create as needed when file/s picked */
/*
<div class='item'>
<img height='100px' width='100px'/><br>
<input type='file'/>
</div>
*/
function onAddBtnClicked(evt)
{
var wrapper = newEl('div');
wrapper.className = 'item';
// var img = newEl('img');
// img.style.height = '100px';
// wrapper.appendChild(img);
var input = newEl('input')
input.type = 'file';
// input.multiple = 'true'; // file-inputs are single-selection only be default.
input.addEventListener('change', onFileChanged, false);
input.name = 'inputFiles[]'; // all inputs to get same name. Name to include [] so php can retrieve all files
wrapper.appendChild(input);
byId('previewHolder').appendChild(wrapper);
}
function onFileChanged(evt)
{
var numFiles = this.files.length;
var itemWrapper = this.parentNode;
var fileInput = this;
if (numFiles == 0)
{
// no files chosen, so remove this preview/file-picker element
var previewHolder = itemWrapper.parentNode;
previewHolder.removeChild(itemWrapper);
}
else
{
// remove all/any existing images
while (allByTag('img', itemWrapper).length != 0)
itemWrapper.removeChild( allByTag('img', itemWrapper)[0] );
forEach(this.files, loadAndPreviewImage);
function loadAndPreviewImage(fileObj)
{
loadFileObject(fileObj, onFileObjLoaded);
function onFileObjLoaded(evt) //.target.result;
{
var img = newEl('img');
img.style.height = '100px';
img.src = evt.target.result;
itemWrapper.insertBefore(img, fileInput);
}
}
}
}
.item
{
border: solid 1px black;
border-radius: 6px;
padding: 4px;
}
.button:hover
{
background-color: #b0ffb0;
cursor: pointer;
}
<div id='previewHolder' style='width: 200px'>
<div class='button' id='addBtn' style='text-align:center;padding: 4px'><svg xmlns="http://www.w3.org/2000/svg" height="32" width="32" viewBox="0 0 32 32">
<g transform="translate(0 -1020)" stroke="#00c03b" fill="none">
<circle cx="16" cy="1036" r="14.5" stroke-width="2.998"/>
<path d="m8 1036h16" stroke-linecap="round" stroke-width="3"/>
<path d="m16 1044v-16" stroke-linecap="round" stroke-width="3"/>
</g>
</svg></div>
</div>

Comparing width and height of uploaded picture

I have a file input (picture) and I want to set its div's class depending on what is bigger: its width or its height.
My code is not working (only the last if statement), the div's class never changes, regardless to the uploaded image.
This is my HTML:
<div class="row">
<div class="col-md-12">
<div id="blah" class="profilePic">
<img src="profilkep.jpg" />
</div>
</div>
</div>
<br>
<div class="row">
<div class="col-md-12">
<input type="file" onchange="previewFile()">
</div>
</div>
And this is my JavaScript:
function previewFile(){
var preview = document.querySelector('img'); //selects the query named img
var file = document.querySelector('input[type=file]').files[0]; //sames as here
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
reader.readAsDataURL(file); //reads the data as a URL
} else {
preview.src = "";
}
if (file.width < file.height) {
document.getElementById("blah").setAttribute("class", "blahblah");
} else {
document.getElementById("blah").setAttribute("class", "profilePic");
}
}
Your code seems fine. Here's a working snippet
function previewFile(){
var preview = document.querySelector('img'); //selects the query named img
var file = document.querySelector('input[type=file]').files[0]; //sames as here
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
reader.readAsDataURL(file); //reads the data as a URL
} else {
preview.src = "";
}
if (file.width < file.height) {
document.getElementById("blah").setAttribute("class", "blahblah");
} else {
document.getElementById("blah").setAttribute("class", "profilePic");
}
}
.blahblah {
border: 1px solid red;
}
.profilePic {
border: 1px solid blue;
}
<div class="row">
<div class="col-md-12">
<div id="blah" class="profilePic">
<img src="http://i.imgur.com/MxPGcXu.gif" />
</div>
</div>
</div>
<br>
<div class="row">
<div class="col-md-12" id="blah">
<input type="file" onchange="previewFile()">
</div>
</div>
The problem is that you have two same IDs blah. All ids need to be unique.
file.width and file.height are always undefined. Here is the fix:
<div class="row">
<div class="col-md-12">
<div id="blah">
<img id="profileImage" src="profilkep.jpg" />
</div>
</div>
</div>
<br>
<div class="row">
<div class="col-md-12">
<input type="file" onchange="previewFile()">
</div>
</div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript">
function previewFile(){
var preview = document.querySelector('img'); //selects the query named img
var file = document.querySelector('input[type=file]').files[0]; //sames as here
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
var imageWidth = $('#profileImage').width();
var imageHeight = $('#profileImage').height();
if (imageWidth < imageHeight) {
console.log('width < height');
document.getElementById("blah").setAttribute("class", "blahblah");
} else {
console.log('width > height');
document.getElementById("blah").setAttribute("class", "profilePic");
}
}
if (file) {
reader.readAsDataURL(file); //reads the data as a URL
} else {
preview.src = "";
}
}
</script>

how to preview an image before uploading and replace it with older image after uploading in javascript

Hai i am trying to preview an image before it uploading to server and have to replace it with older image.
here is my html code:::::::
<img class=" thumbnail" data-ng-hide="imageSource==NULL" style="width: 200px; height: 150px;" ng-hide="user.pic" ng-src="{{imageSource}}">
<img class="hai thumbnail img-responsive" style="width: 200px; height: 150px;" data-ng-show="!imageSource" ng-src="{{user.pic}}">
<div >
<span class="btn btn-default btn-file">
<span class="fileinput-new upload-button"><span class="glyphicon glyphicon-upload"></span> select image</span>
<input class="file-upload" ng-model="user.pic" id="FilePhoto" onchange="angular.element(this).scope().file_changed(this)" type="file" accept="image/*" multiple />
</span>
<button type="button" class="btn btn-large btn-primary" ng-click="upload()">upload me
</button>
my script code looks like this.......
$scope.file_changed = function (element) {
console.log('llllllll');
var files = element.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, photofile; photofile = files[i]; i++) {
var photofile = element.files[0];
var reader = new FileReader();
reader.onload = (function (theFile) {
return function (e) {
$('#blah').attr('src', e.target.result);
$rootScope.imageSource = e.target.result;
console.log('lllllllldddddddddddddd' + JSON.stringify($scope.imageSource));
$scope.img=true;
};
})(photofile);
reader.readAsDataURL(photofile);
};
}
controller for uploading image.............
$scope.upload = function () {
console.log('imageeeee' + JSON.stringify($rootScope.imageSource));
var image = {
pic: $rootScope.imageSource,
};
userss.updateimage.update(image, function (result) {
console.log("sucessfully image uploaded" + JSON.stringify(result));
});
}
please help me to solve this problem. every thing working good but i cant able to preview image

Categories