View and Hide Image Using Jquery - javascript

I am displaying images before upload using jquery, when i upload some new files i want to remove or hide the previous upload files here's my jquery code:
$(function()
{
// Multiple images preview in browser
var imagesPreview = function(input, placeToInsertImagePreview)
{
if (input.files)
{
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++)
{
var reader = new FileReader();
reader.onload = function(event)
{
$($.parseHTML('<img class="p-3" width="350px" height="250px">')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
}
reader.readAsDataURL(input.files[i]);
}
}
}
$('#file_input').on('change', function()
{
imagesPreview(this, 'div#viewUploadItems');
});
});
And my HTML Code:
<input type="file" name="images[]" id="file_input" class="deletable" multiple />
<div id="viewUploadItems"></div>
I try this code but this won't display any image.
$("#file_input").on("click",function()
{
$('input.deletable').val('');
$('#viewUploadItems').remove();
});

Perhaps you could take the following approach, where in your imagePreview() function you:
first call empty() on the preview selector to clear any prior image contents
then proceed to read and display any selected images, by using the FileReader API as you currently are (see below for revised approach)
Also, consider checking the type of the file object, to ensure that it is an image before attempting to display it via the following:
if (file.type.match("image.*")) {
/* file is image type, so attempt to preview it */
}
Bringing these ideas together, you could revise your code as follows:
$(function() {
function imagesPreview(input, targetSelector) {
/* Empty the target area where previews are shown */
$(targetSelector).empty();
/* Iterate each file via forEach in own closure */
Array.from(input.files).forEach(function(file) {
/* If file is image type proceed to preview */
if (file.type.match("image.*")) {
/* Create filereader and set it up for reading */
var reader = new FileReader();
reader.onload = function(event) {
/* Append a new image element, prepopulated with
required attrbutes, and assigned with p-3 class */
$(targetSelector).append($('<img>', {
width: '350px',
height: '250px',
src : reader.result
}).addClass('p-3'))
}
reader.readAsDataURL(file);
}
})
}
$('#file_input').on('change', function() {
imagesPreview(this, 'div#viewUploadItems');
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="file" name="images[]" id="file_input" class="deletable" multiple />
<div id="viewUploadItems"></div>

Easier to clear the div before display : $(placeToInsertImagePreview).html("");
$(function()
{
// Multiple images preview in browser
var imagesPreview = function(input, placeToInsertImagePreview)
{
if (input.files)
{
$(placeToInsertImagePreview).html("");
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++)
{
var reader = new FileReader();
reader.onload = function(event)
{
$($.parseHTML('<img class="p-3" width="350px" height="250px">')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
}
reader.readAsDataURL(input.files[i]);
}
}
}
$('#file_input').on('change', function()
{
imagesPreview(this, 'div#viewUploadItems');
});
});

Related

How can I count appended elements and calculate their style?

I'm trying to create a local static page with an image uploader and a preview gallery to which append images while the user selects them. To be more specific, the image uploader is an <input type="file" multiple="multiple"> and whenever a user selects an image I have a <div class="preview__gallery"></div> to which I append the selected images from the File Explorer.
Here comes the problem. After the <img> tags are being attached to the gallery div I'd like to count them using jQuery .length property so I can then apply some custom style using .css() based on the counting results.
Seems like I can not target those images by class. I've read all across the internet and even here on SO for similar anwers and in fact I've already tried a lot of options. I've tried to use jQuery deferred functions with $.when(firstFunction()).done(otherFunction()), I've tried to use MutationObserver to control changes that occurs on the gallery div and I've also tried event delegation but without success because I don't have any event that triggers the function. It just have to start after the images are appended.
I'm currently calling the counting function as a callback after the function that appends the images. I put a console.log('before') on the first function and a console.log('after') on the counting one, and it seems that the callback is working correctly. However, the .length property is not working and this is because jQuery is not being able to target the image element on the DOM. In fact, using a console.log($('.preview__thumb')) outputs an empty jQuery object.
Here's the HTML:
<div class="concorso__body">
<div class="container">
<div class="row">
<div class="col-lg-8">
<div class="single__upload">
<div class="upload__field">
<input type="file" accept="image/*" multiple="multiple" class="drag__area" id="file__input">
<div class="upload__text">
<i class="bi bi-plus"></i>
<span>Trascina o clicca per caricare immagini</span>
</div>
</div>
<div class="preview__gallery" id="the__gallery"></div>
</div>
</div>
<div class="col-lg-4"></div>
</div>
</div>
</div>
And here's the JS (using jQuery):
$(document).ready(function() {
$(function() {
function imagesPreview(input, placeToInsertImagePreview, callback) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img class="preview__thumbs">')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
};
reader.readAsDataURL(input.files[i]);
console.log('before');
}
if(typeof callback === 'function') {
callback();
}
}
}
});
});
$(document).ready(function() {
$(function() {
function imagesPreview(input, placeToInsertImagePreview, callback) {
if (input.files) {
var filesAmount = input.files.length;
var count = 0; // Initialize a counter for the number of images
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img class="preview__thumb">')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
count++; // Increment the counter after each image is added
if (count == filesAmount) { // Check if all images have been added
if (typeof callback === 'function') {
callback();
}
}
};
reader.readAsDataURL(input.files[i]);
}
}
}
// Call the imagesPreview function on file input change event
$('#file__input').on('change', function() {
var gallery = $('.preview__gallery');
imagesPreview(this, gallery, function() {
// This function is called after all images have been appended
var numImages = $('.preview__thumb').length;
console.log(numImages); // This should output the correct number of images
if (numImages > 5) {
gallery.css('background-color', 'red'); // Apply custom style if more than 5 images
}
});
});
});
});

Hide image preview on input click/change

I have created a image preview in JavaScript with some script i found here, I'm new to JS and now I am trying to replace the content instead of appending it. Here is the code
I've tried to put empty(), replaceWith(), remove(), just before appendTo() like other similar questions on SO, I've tried to create a function to hide the div, and nothing seems to work. I was wondering if anyone would know why these functions doesn't work, Am i doing something wrong?
//my html/php
echo '<input required type="file" name="filesToUpload[]" multiple
id="image_upload" accept=".jpg, .jpeg">';
echo '<div id="gallery-preview" class="gallery-preview"></div>';
//javascript
$(function() {
var imagesPreview = function(input, placeToInsertImagePreview) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img style="width:150px; height:75px; margin-left:2px; margin-right:2px; border:1px solid black; padding:2px;">')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
}
reader.readAsDataURL(input.files[i]);
}
}
};
$('#image_upload').on('change', function() {
imagesPreview(this, 'div.gallery-preview');
});
});
When i create a function to hide() the div gallery-preview, the preview doesn't work anymore. Same for other functions mentioned above
I think you are trying to set it empty each time you run the function.
Modify the change function in your code to the following
$('#image_upload').on('change', function() {
//this line will set the contents to empty before you run your function
$('div.gallery-preview').html('');
//now call your function
imagesPreview(this, 'div.gallery-preview');
});

how to show thumbnails of dropped images before submit

<div class="top-main-section">
<%= form_for #usr_vendor_web_slide ,url:{action: "slidecreate"} , html: {class: "form-horizontal"} do |f| %>
<div class="top-main-section-area">
<div id="upload-area" class="uploader1" onclick="$('#post_image').click()">
<%= f.file_field :images, :onchange => 'readURL(this)', class:'slide-img', multiple: true, id:'slide-img'%>
<img id="slide_image" src="#" alt="image" style="display: none;" class="slide_image" />
</div>
</div>
<%= f.submit({:class => 'btn btn-primary'}) %>
<% end %>
</div>
<div id="thumbnail" class="thumbnail">
<img id="slide_image1" src="#" alt="" style="" />
</div>
javascript file
var data = [];
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
var ids = $("#slide_image");
insert();
function insert() {
var id;
id = ids;
data.push({
id: id,
});
clearAndShow()
}
function clearAndShow() {
// Clear our fields
ids = "";
console.log(data)
}
reader.onload = function(e) {
$("#slide_image").style.display = 'block';
$('#slide_image').attr('src', e.target.result).width(1000).height(480);
$("#slide_image").style.display = 'block';
$('#slide_image1').attr('src', e.target.result).width(100).height(100);
};
reader.readAsDataURL(input.files[0]);
}
}
I'm try to show images thumbnails before submit . I'll success in current dropped image show in top main section area and show it's thumbnail in thumbnail part. but i want to show all thumbnails in thumbnail part before submit. I'll try to make a javascript array and store images in that array. but i cannot get image src to show in thumbnail part. appreciate your ideas
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
document.getElementById("slide_image").style.display = 'block';
$('#slide_image')
.attr('src', e.target.result)
.width(1000)
.height(480);
};
reader.readAsDataURL(input.files[0]);
}
}
window.onload = function() {
document.getElementById('files').addEventListener('change',
handleFileSelect, false);
function handleFileSelect(evt) {
console.log("hariii");
var files = evt.target.files;
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function (theFile) {
return function (e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML =
[
'<img style="height: 75px; border: 1px solid #000;
margin: 5px" src="',
e.target.result,
'" title="', escape(theFile.name),
'"/>'
].join('');
document.getElementById('thumbnail').insertBefore(span,
null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
}
this is my solution and it works fine for my proect
Showing Thumbnail preview for the images which user selected to upload will help user to make sure they are selected the right images. Here is the code which can show preview of images as thumbnail for the selected objects. You can try either selecting or drag and drop for previewing the images.
This code uses the HTML5 features and may not work with old browsers. The two main HTML5 features used by this code are FileReader and Canvas.
Javascript
jQuery(function($){
var fileDiv = document.getElementById("upload");
var fileInput = document.getElementById("upload-image");
console.log(fileInput);
fileInput.addEventListener("change",function(e){
var files = this.files
showThumbnail(files)
},false)
fileDiv.addEventListener("click",function(e){
$(fileInput).show().focus().click().hide();
e.preventDefault();
},false)
fileDiv.addEventListener("dragenter",function(e){
e.stopPropagation();
e.preventDefault();
},false);
fileDiv.addEventListener("dragover",function(e){
e.stopPropagation();
e.preventDefault();
},false);
fileDiv.addEventListener("drop",function(e){
e.stopPropagation();
e.preventDefault();
var dt = e.dataTransfer;
var files = dt.files;
showThumbnail(files)
},false);
function showThumbnail(files){
for(var i=0;i<files.length;i++){
var file = files[i]
var imageType = /image.*/
if(!file.type.match(imageType)){
console.log("Not an Image");
continue;
}
var image = document.createElement("img");
// image.classList.add("")
var thumbnail = document.getElementById("thumbnail");
image.file = file;
thumbnail.appendChild(image)
var reader = new FileReader()
reader.onload = (function(aImg){
return function(e){
aImg.src = e.target.result;
};
}(image))
var ret = reader.readAsDataURL(file);
var canvas = document.createElement("canvas");
ctx = canvas.getContext("2d");
image.onload= function(){
ctx.drawImage(image,100,100)
}
}
}
});
HTML
<input type="file" style="display:none" id="upload-image" multiple="multiple"></input>
<div id="upload" class="drop-area">
Upload File
</div>
<div id="thumbnail"></div>
CSS
.drop-area{
width:100px;
height:25px;
border: 1px solid #999;
text-align: center;
padding:10px;
cursor:pointer;
}
#thumbnail img{
width:100px;
height:100px;
margin:5px;
}
canvas{
border:1px solid red;
}

Show image preview until upload

I test this script, see here. But I can't do working, because when select image, only show codes no the image.
<script>
jQuery(document).ready(function(e){
jQuery('#file_input').change(function(e) {
//alert("okokok");
/**/
readFile(this.files[0], function(e) {
//manipulate with result...
jQuery('#output_field').text(e.target.result);
});
});
});
function readFile(file, callback){
var reader = new FileReader();
reader.onload = callback
reader.readAsText(file);
}
</script>
HTML Code :
> <input type="file" id="file_input" class="foo" /> <div
> id="output_field" class="foo"></div>
When select the file I want, only show encode words and numbers, not the image. I don't know how or why does this happen?
Try this code:
jQuery(document).ready(function(e){
jQuery('#file_input').change(function(e) {
//alert("okokok");
/**/
readFile(this.files[0], function(e)
{
//manipulate with result...
jQuery('#output_field').src(e.target.result);
});
});
});
function readFile(file, callback){
var reader = new FileReader();
reader.onload = callback
reader.readAsDataURL(file);
}
This assumes that #output_field is an image, otherwise you should change it to an img element.
This article can be helpful: http://www.javascripture.com/FileReader

Display a spinner as img src attribute is set using FileReader()

I'm using the following code to read a image file and set the result as the src for an image attribute,
document.getElementsByClassName("upload-image"),
function(fileElement) {
var previewElement = document.createElement("img");
previewElement.style.display = "block";
fileElement.parentNode.insertBefore(previewElement, fileElement);
var fileReader = new FileReader();
fileReader.onload = function(event) {
previewElement.src = event.target.result;
};
fileElement.addEventListener("change", updateImagePreview, false);
updateImagePreview();
function updateImagePreview() {
var file = fileElement.files[0];
if (file) {
fileReader.readAsDataURL(file);
} else {
var placeholderSrc = fileElement.getAttribute("data-placeholder");
if (placeholderSrc) {
previewElement.src = placeholderSrc;
} else {
previewElement.removeAttribute("src");
}
}
}
}
This works well, however I know that it takes some time for the actual image src to be set and for the image to be displayed.
Is there anyway for me to detect when the image src is set, and loaded, and ready to be displayed?

Categories

Resources