Comparing width and height of uploaded picture - javascript

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>

Related

How can I run function within content in Tooltipster?

I'm using the tooltipster plugin to create a tooltip. And I would like to run this function in the content:
Function:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]); // convert to base64 string
}
}
$("#imgInp").change(function() {
readURL(this);
});
But since, content should be string, how could I possibly run this function for content?
Here's my setup for Tooltipster. I would like to apply the function to the form.
Content:
const imageTooltipTemplate =
`<div><h4>Put new image URL:</h4>
<div class="se-tooltip-content">
<p><b>Notice: </b>not in all cases the image will be in the same size as the original image</p>
<input class="tooltip-content"></input>
<form runat="server">
<input type='file' id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>
<div class="se-action-container">
<button class="cancel-button se-btn">
<div>Cancel</div>
<div class="small-text-btn">(or ESC key)</div>
</button>
<button class="ok-button se-btn">OK</button>
</div>
</div>
</div>`;
Switch:
const getTooltip = (prop) => {
switch (prop.toLowerCase()) {
case 'img':
return imageTooltipTemplate;
....
Tooltipster:
let template = getTooltip(this.type);
this.$element
.tooltipster({
interactive: true,
trigger: 'custom',
triggerClose: {
click: true,
},
content: $(template),
})
.tooltipster('open');
Done.
I just need to add
const imageTooltipTemplate =
`<div><h4>Put new image URL:</h4>
<div class="se-tooltip-content">
<p><b>Notice: </b>not in all cases the image will be in the same size as the original image</p>
<input class="tooltip-content"></input>
<form runat="server">
<input type='file' id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>
<div class="se-action-container">
<button class="cancel-button se-btn">
<div>Cancel</div>
<div class="small-text-btn">(or ESC key)</div>
</button>
<button class="ok-button se-btn">OK</button>
</div>
</div>
</div>
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]); // convert to base64 string
}
}
$("#imgInp").change(function() {
readURL(this);
});
</script>
`;

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 prevent this Multiple drag and drop image file from duplicate

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

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

addEventListener click function does not work

I needed to save an html table's content in a .txt file. So I found this example:
page.html:
<html>
<body>
<div>
<textarea id="textbox">Type something here</textarea>
<button id="create">Create file</button>
<a download="info.txt" id="downloadlink" style="display: none">Download</a>
</div>
</body>
create.js:
(function () {
var textFile = null,
makeTextFile = function (text) {
var data = new Blob([text], {type: 'text/plain'});
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';
}, false);
})();
This code has a text area. When you click the botton it creates a "Download" link and by clicking it you can download the text area content as a txt file.
I am trying to implement a very similar function. Only difference is I get my string from an html table. Here is the code:
html:
<div class="container">
<div class="row" style="">
<section class="module span12" style="top: 50px">
<div class="module-body">
<button type="button" class="btn-blue"
style="top: 80px; right: 130px;" onclick="loadOutputs()">Load
Outputs</button>
<button class="btn btn-blue" id="save" onclick="createText()"
style="top: 80px; right: 130px;">Save</button>
<a download="info.txt" id="downloadlink" style="display: block">Download</a>
<div id="loadingElement" class="loaded">
<table>
<tbody id="tbody"></tbody>
</table>
</div>
</div>
</section>
</div>
<div class="row"></div>
javascript:
function createText() {
var text = '';
var table = document.getElementById("tbody");
if (table) {
for ( var i = 0, row; row = table.rows[i]; i++) {
text = text.concat(row.innerText);
}
}
var textFile = null, makeTextFile = function(text) {
var data = new Blob([text], {type: 'text/plain'});
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
return textFile;
};
var create = document.getElementById('save');
create.addEventListener('click', function() {
var link = document.getElementById('downloadlink');
link.href = makeTextFile(text);
link.style.display = 'block';
}, false);
}
In the js code, when I debug, I see that it successfully fills the text variable with the contents of the table, but cannot get into create.addEventListener().
Inside the function variable link seems to be 'undefined', so I make the assumption that it cannot get inside of the function. What might be the problem?
The problem here is, you have a function called createText which is having all your code including the save handler... then your button's onclick attribute is calling the createText function....
In the above working sample the actual code is in a IIFE block which is executed on page load... so you need to either use a IIFE or call the function createText on page load and remove onclick="createText()" from the button since the actual click handler is registered using script. so
(function(){
var textFile = null,
makeTextFile = function (text) {
var data = new Blob([text], {
type: 'text/plain'
});
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
return textFile;
};
var create = document.getElementById('save');
create.addEventListener('click', function () {
var text = '';
var table = document.getElementById("tbody");
if (table) {
for (var i = 0, row; row = table.rows[i]; i++) {
console.log('a')
text = text.concat(row.innerText);
}
}
var link = document.getElementById('downloadlink');
link.href = makeTextFile(text);
link.style.display = 'block';
}, false);
})()
<table>
<tbody id="tbody">
<tr>
<td>1.1</td>
</tr>
<tr>
<td>2.1</td>
</tr>
</tbody>
</table>
<div class="container">
<div class="row" style="">
<section class="module span12" style="top: 50px">
<div class="module-body">
<button type="button" class="btn-blue"
style="top: 80px; right: 130px;" onclick="loadOutputs()">Load
Outputs</button>
<button class="btn btn-blue" id="save"
style="top: 80px; right: 130px;">Save</button>
<a download="info.txt" id="downloadlink" style="display: block">Download</a>
<div id="loadingElement" class="loaded">
<table>
<tbody id="tbody"></tbody>
</table>
</div>
</div>
</section>
</div>
<div class="row"></div>
</div>

Categories