I'm working on uploading multiple images one at a time by dynamically generating the input field and image element. However, my code doesn't display the images on the dynamically generated image element.
<button type="button" class="btn btn-sm btn-info add-image"><i class="ti-image"></i> Add image</button>
<br><br>
<div class="images"></div>
$(document).ready(function() {
var max_image = 10;
var count = 1;
$('.add-image').click(function(e) {
e.preventDefault();
if (count < max_image) {
count++;
$('.images').append(`<div class="input" style="width:100px;height:120px;border:2px dashed lightgrey;float:left;margin:8px">
<input type ="file" class ="fileup 1" id ="file'+count+'" style="width:100%; height:100%; opacity:0; position: absolute">
<img id ="image'+count+'" src="" style="width:100%; height:100%;">
<span class="btn btn-sm btn-danger delete" style="position:relative;bottom:20px"><I class="ti-trash"></i></span>
</div>`);
$(document).on('change', '#file' + count, function() {
readURL(this);
});
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#image' + count).attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
} else {
alert("Only a maximum of 10 images is allowed");
}
});
$('.images').on("click", ".delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
y--;
})
});
Instead of making event handler for all files use can just one event handler and then inside your readURL function use .closest('div').find('img') to add src to image tag.
Demo Code :
$(document).ready(function() {
// allowed maximum input fields
var max_image = 10;
// initialize the counter for textbox
var count = 1;
// handle click event on Add More button
$('.add-image').click(function(e) {
e.preventDefault();
if (count < max_image) {
count++; // increment the counter
// validate the condition
$('.images').append(`<div class="input" style="width:100px;height:120px;border:2px dashed lightgrey;float:left;margin:8px">
<input type ="file" class ="fileup 1" id ="file'+count+'" style="width:100%; height:100%; opacity:0; position: absolute">
<img id ="image'+count+'" src="" style="width:100%; height:100%;">
<span class="btn btn-sm btn-danger delete" style="position:relative;bottom:20px"><I class="ti-trash"></i></span>
</div>`); // add input field
} else {
alert("Only a maximum of 10 images is allowed");
}
});
// handle click event of the remove link
$('.images').on("click", ".delete", function(e) {
e.preventDefault();
$(this).parent('div').remove(); // remove input field
y--; // decrement the counter
})
//put this outside..
$(document).on('change', '.images input[type=file]', function() {
readURL(this);
});
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
//get closest div and then find img add img there
$(input).closest('div').find('img').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn btn-sm btn-info add-image"><i class="ti-image"></i> Add image</button>
<br><br>
<div class="images"></div>
There's several issues to address here.
Don't nest your event handlers
Put CSS rules in an external stylesheet, not inline in the HTML
You're not appending the count value to the template literal using the correct syntax
Aside from the above, do not use incremental id attributes. Group elements with common behaviour by class and attach a single event handler to them all. This is what you should do with the delegated event handler you're using.
The latter point is what fixes your issue, as it will allow you to target the img which was clicked on and update its specific src attribute to the content of the file which was selected.
$(document).ready(function() {
var max_image = 10;
$(document).on('change', '.fileup', function() {
readURL(this, $(this).next('img'));
});
function readURL(input, $target) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$target.attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$('.add-image').click(function(e) {
e.preventDefault();
if ($('div.input').length < max_image) {
$('.images').append(`<div class="input">
<input type="file" class="fileup" />
<img />
<span class="btn btn-sm btn-danger delete">
<i class="ti-trash">X</i>
</span>
</div>`);
} else {
alert("Only a maximum of 10 images is allowed");
}
});
$('.images').on("click", ".delete", function(e) {
e.preventDefault();
$(this).closest('div').remove();
})
});
div.input {
width: 100px;
height: 120px;
border: 2px dashed lightgrey;
float: left;
margin: 8px;
}
input.fileup {
width: 100%;
height: 100%;
opacity: 0;
position: absolute;
}
div.input img {
width: 100%;
height: 100%;
}
span.delete {
position: relative;
bottom: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn btn-sm btn-info add-image">
<i class="ti-image"></i>
Add image
</button>
<br><br>
<div class="images"></div>
Related
a beginner here, i'm trying to make a modal that will be shown once the share button is clicked and i don't seem to find why the onclick function isn't executed, the idea is once the share button is clicked the display:none; will be changed to display:block, so either there is a problem with style.display="block" or, which is more probable, i suck .
Any help is appreciated.
Thank you previously.
HTML code:
<div class="navbar-container">
<div class="nav nav-1" >
<button class="btn btn-1" id="sharebtn">Share </button>
</div>
<div class="nav nav-2">
<button class="btn btn-2" id="howbtn">how does it work ?</button>
</div>
<div class="nav nav-3" >
<button class="btn btn-3" id="abouttns">About</button>
</div>
</div>
<!---Creating the modals-->
<div id="modal-share">
<div class="modal-header">
<button class="close-share">×</button>
</div>
<div class="link">
<input type="text" class="link-input" placeholder="www.youtube.com/jdlkfsjakfdsa">
<button id="share-btn" onclick="fuck">share</button>
</div>
<div class="description">
<input type="text" max="50" placeholder="cats are not that smart">
</div>
</div>
CSS code:
#modal-share{
display: none; /*hidden by default*/
position: fixed; /*staying in the center even when scrolling*/
z-index: 1; /*stays on top of grids, 3D translation*/
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: white; /*color of the modal*/
background-color: rgba(0,0,0,0.4); /*color of the background*/
border:1px solid black;
}
Javascript code:
<script>
var modal=document.getElementById("modal-share");
var share_btn=document.getElementsById("sharebtn");
var close_share=document.getElementsByClassName("close-share");
share_btn.onclick=function(){
modal.style.display="block";
}
close_share.onclick=function(){
modal.style.display="none";
}
window.onclick=function(event){
if(event.target==modal){
modal.style.display="none";
}
}
</script>
There is actually an error in your script which is causing everything else to fail, namely
var share_btn=document.getElementsById("sharebtn");
There is no function document.getElementsById, only document.getElementById. I have your code working with the fix on the following link -
https://jsfiddle.net/2pfzc4gL/
There is a typo in your script which is causing the issue.
var share_btn=document.getElementsById("sharebtn");
it should be getElementById instead of getElementsById.
it would be better if we use querySelector for querying DOM element and for events addEventListener instead of overriding the click function
var share_btn = document.querySelector("#sharebtn");
var close_share = document.querySelector(".close-share");
var modal = document.querySelector("#modal-share");
share_btn.addEventListener("click", function () {
modal.style.display = "block";
});
close_share.addEventListener("click", function () {
modal.style.display = "none";
});
window.addEventListener("click", function (event) {
if (event.target == modal) {
modal.style.display = "none";
}
});
Two things, first there's a typo in your code getElementsById should be getElementById. And the second is that getElementsByClassName returns an array like collection of elements so you need to retrieve the first one from the array. Here's the updated javascript.
const modal = document.getElementById("modal-share");
const share_btn = document.getElementById("sharebtn"); // typo here in original
const close_share = document.getElementsByClassName("close-share")[0]; // select first element in HTML collection
share_btn.onclick = function () {
modal.style.display = "block";
}
close_share.onclick = function () {
modal.style.display = "none";
}
window.onclick = function (event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
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>
hello i have an image upload with image preview, when user upload image, a button remove show up for cancel that image(the image user upload) and switch to back to image default(for this case placeholder image), and the button remove got hidden because input file didnt have any value.
for now i success to show up the button when user upload. but when user click the remove. only the button remove got hidden, but the image still there. how to make the image back to placeholder when user click remove?
this is my code
$(document).ready(function() {
$(".input-file").on("change", function(){
if($(this).val() == "") {
$(this).parent().find(".image-upload-footer").css({"display": "none"});
} else {
$(this).parent().find(".image-upload-footer").css({"display": "block"});
}
});
$(".reset").click(function(){
$(this).closest(".image-upload").parent().find(".input-file").val("").trigger('change');
});
});
this is the jsfiddle https://jsfiddle.net/uxsxuwzd/1/
thankyou
Please replace this code in your functions. You should have to reset the selected src of input file.
This is for multiple type of images in dimension.
$(document).ready(function() {
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#image_upload_preview1').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#inputFile1").change(function () {
readURL(this);
});
});
$(document).ready(function() {
function readURLs(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#image_upload_preview2').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#inputFile2").change(function () {
readURLs(this);
});
});
$(document).ready(function() {
$(".input-file").on("change", function(){
if($(this).val() == "") {
$(this).parent().find(".image-upload-footer").css({"display": "none"});
} else {
$(this).parent().find(".image-upload-footer").css({"display": "block"});
}
});
$(".reset").click(function(){
$(this).closest(".image-upload").parent().find(".input-file").val("").trigger('change');
var newImg=$(this).attr('custattr');
$("#"+$(this).closest(".image-upload").parent().find(".img-responsive").attr('id')).attr("src",newImg);
});
});
.image-upload-footer p{
display: inline
}
.image-upload input[type=file]{
display: none;
}
.image-upload label{
margin-bottom: 0;
}
.image-upload img{
cursor: pointer;
}
.profileback .deleteThis{
position: absolute;
top: 6px;
right: 21px;
padding: 0;
}
.deleteThis span{
color: #fff
}
.image-upload-footer{
background-color: rgba(34, 34, 34, 0.87);
margin-top: -6px;
padding: 4px 10px;
}
.image-upload-footer button{
padding: 0px 5px;
border-radius: 100%;
margin-left: 15px;
}
.image-upload-footer button span,.image-upload-footer p{
color: #fff ;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<div class="col-xs-6">
<div class="image-upload">
<label for="inputFile1">
<img id="image_upload_preview1" class="img-responsive mainPic" src="http://placehold.it/350x150"/>
</label>
<input id="inputFile1" class="input-file" type="file"/>
<div class="image-upload-footer" style="display:none">
<button type="reset" custattr="http://placehold.it/350x150" class="btn btn-red reset">
<span class="fa fa-times"aria-hidden="true">X</span>
</button>
<p>remove</p>
</div>
</div>
</div>
<div class="col-xs-6">
<div class="image-upload">
<label for="inputFile2">
<img id="image_upload_preview2" class="img-responsive" src="http://placehold.it/746x728" alt=""/>
</label>
<input id="inputFile2" class="input-file" type="file"/>
<div class="image-upload-footer" style="display:none">
<button type="button" custattr="http://placehold.it/746x728" class="btn btn-red reset">
<span class="fa fa-times"aria-hidden="true">X</span>
</button>
<p>remove</p>
</div>
</div>
</div>
This is for one type of images dimension
$(".reset").click(function(){
$(this).closest(".image-upload").parent().find(".input-file").val("").trigger('change');
$("#"+$(this).closest(".image-upload").parent().find(".img-responsive").attr('id')).attr("src","http://placehold.it/350x150");
});
Note:I'm new to javascript.
I have the following code which allows the user to preview an image before uploading it.
The input element works fine and the selected image is displayed as expected.
However, the drag and drop throws an error that,
Uncaught TypeError: Cannot read property 'files' of undefined
I think I am taking the dropped file object in a wrong way any help would be greatly appreciated.
(function($){
$(document).ready(function(){
function renderImage(file)
{
var reader = new FileReader();
reader.onload = function(event) {
the_url = event.target.result
$('#preview').html("<img width='150px' height = '100px'src='" + the_url + "' />")
}
reader.readAsDataURL(file);
}
//This is for the input and works fine.
$('#file').change( function (){
renderImage(this.files[0])
});
//The drag is the one with problem.
//it produces the following error
/*
*Uncaught TypeError: Cannot read property 'files' of undefined
*/
$("#drop").on('dragenter', function (e){
e.preventDefault();
$(this).css('background', '#BBD5B8');
});
$("#drop").on('dragover', function (e){
e.preventDefault();
});
$("#drop").on('drop', function (e){
$(this).css('background', '#D8F9D3');
e.stopPropagation();
e.preventDefault();
var dt = e.target.files || (e.dataTransfer && e.dataTransfer.files);
var files = dt.files;
renderImage(files);
});
});
})(jQuery)
#drop
{
width:300px;
height:100px;
border:dotted 1px;
border-radius:5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id = "upload">
<div id = "drop">
</div>
<input type ="file" id = "file">
<div id = "preview">
</div>
</div>
My proposal is, where I corrected also the "Uncaught TypeError: Cannot read property 'files' of undefined" (only for FF it's necessary to double the input field):
(function($){
$(document).ready(function() {
function renderImage(file)
{
var reader = new FileReader();
reader.onload = function(event) {
the_url = event.target.result
$('#preview').html("<img width='150px' height = '100px'src='" + the_url + "' />")
}
reader.readAsDataURL(file);
}
//This is for the input and works fine.
$('input[type^="file"]').change( function (){
renderImage(this.files[0])
});
//The drag is the one with problem.
//it produces the following error
/*
*Uncaught TypeError: Cannot read property 'files' of undefined
*/
$("#drop").on('dragenter', function (e){
event.target.style.background = '#BBD5B8';
});
$("#drop").on('dragover', function (e){
e.preventDefault();
});
$("#drop").on('drop', function (e){
event.target.style.background = '#D8F9D3';
e.stopPropagation();
e.preventDefault();
var dt = (e.originalEvent.target.files && e.originalEvent.target.files.length > 0) || (e.originalEvent.dataTransfer && e.originalEvent.dataTransfer.files);
var files = dt[0];
renderImage(files);
});
});
})(jQuery);
#drop
{
width:300px;
height:100px;
border:dotted 1px;
border-radius:5px;
}
#drop input {
position: absolute;
top: 0;
right: 0;
cursor: pointer;
opacity: 0.0;
filter: alpha(opacity=0);
font-size: 300px;
height: 100px;
}
#drop label {
position: absolute;
top: 40px;
width: 250px;
text-align: center;
}
<script src="http://code.jquery.com/jquery-1.11.3.js"></script>
<div id="upload">
<div id="drop">
<label id="fileLbl">Drop a file here</label>
<input type ="file" id = "file1">
</div>
<input type ="file" id = "file2">
<div id = "preview">
</div>
</div>
I believe the issue is with your HTML. Try moving your input inside of your #drop div
<div id = "upload">
<div id = "drop">
<input type ="file" id = "file">
</div>
<div id = "preview">
</div>
</div>
I am trying to show images on a link click and hiding that image if clicked outside. After trying so many solutions for this I have came up with like below code.
<script>
function setImageVisible(id, visible) {
var img = document.getElementById(id);
img.style.visibility = (visible ? 'visible' : 'hidden');
}
</script>
<div id="wrapper" style="margin-top: -5px; text-align:center" align="center" onclick="javascript:setImageVisible('popup1', false)">
<div id="Btn7"></div>
<img id="popup1" class="img_popup1" src="../screenshots/pop-up.png" style="visibility:hidden" />
</div>
The above code is working fine. But when I add other image like below, its not working. When I clicked outside then images are not hiding.
<script>
function setImageVisible(id, visible) {
var img = document.getElementById(id);
img.style.visibility = (visible ? 'visible' : 'hidden');
}
$(document).click(function() {
var img1 = document.getElementById('popup1');
var img2 = document.getElementById('popup2');
img1.style.visibility = 'hidden';
img2.style.visibility = 'hidden';
});
</script>
<div id="wrapper" style="margin-top: -5px; text-align:center" align="center">
<div id="Btn7"></div>
<img id="popup1" class="img_popup1" src="../screenshots/pop-up.png" style="visibility:hidden" />
<div id="Btn8"></div>
<img id="popup2" class="img_popup2" src="../screenshots/pop-up2.png" style="visibility:hidden" />
</div>
Can anyone please suggest what should I do ?
You don't need jQuery to do this.
function setImageVisible(id, visible) {
var img = document.getElementById(id);
img.style.visibility = (visible ? 'visible' : 'hidden');
}
function hideAll() {
var img1 = document.getElementById('popup1');
var img2 = document.getElementById('popup2');
img1.style.visibility = 'hidden';
img2.style.visibility = 'hidden';
}
function click(e) {
e.stopImmediatePropagation();
var id, el = this;
while (el) {
el = el.nextSibling;
if (el.nodeName === 'IMG') { // finds the next sibling img element
id = el.id;
el = null;
}
}
hideAll(); // hide all images
setImageVisible(id, true); // show the right one
};
document.addEventListener('click', hideAll);
var btns = document.querySelectorAll('.btn'),
i = 0,
len = btns.length;
for (; i < len; i++) {
btns[i].addEventListener('click', click);
}
img {
width: 100px;
height: 100px;
border: 1px solid black;
}
<div id="wrapper" style="margin-top: -5px; text-align:center" align="center">
<div class="btn" id="Btn7">Image 1</div>
<img id="popup1" class="img_popup1" src="../screenshots/pop-up.png" style="visibility:hidden" />
<div class="btn" id="Btn8">Image 2</div>
<img id="popup2" class="img_popup2" src="../screenshots/pop-up2.png" style="visibility:hidden" />
</div>
Sure, as you have added a tag jquery, I am asking you to do it in a simple way like this:
Snippet:
$(function () {
$(".imgPreview").hide();
$(".unstyled li a").click(function () {
$(".imgPreview").show().find("img").attr("src", $(this).attr("href"));
return false;
});
$("body").click(function () {
$(".imgPreview").hide();
});
});
* {font-family: 'Segoe UI'; margin: 0; padding: 0; list-style: none;}
body {margin: 10px;}
li {margin: 5px;}
.unstyled, .imgPreview {float: left; width: 50%;}
.unstyled, .imgPreview img {max-width: 100%;}
p {margin: 5px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<p>Click on a link to show the respective image. Click outside to hide it!</p>
<p>Also you can right click and open it to open the image in a new tab!</p>
<ul class="unstyled">
<li>350x150</li>
<li>750x150</li>
<li>350x150</li>
<li>100x100</li>
<li>350x150</li>
</ul>
<div class="imgPreview">
<img src="" alt="" />
</div>
Try this simple demo
<!DOCTYPE html>
<html>
<head>
<script src = "jquery-1.10.2.min.js"></script>
</head>
<body>
Click to show image
<img id="image" style="display:none;height:500px; width:500px;">
<script type="text/javascript">
$('#imageLink').click(function (e){
e.stopPropagation();
$('#image').show();
});
$('body').click(function () {
$('#image').hide();
})
</script>
</body>
</html>
Remove inline event handler and write for common click event ,
1) bind the click event for all a tag inside wrapper id and then show the images when link is clicked
2) bind the click event for document and hide the all images when clicking outside of link
$("#popup1,#popup2").hide();
$("#Btn7,#Btn8").click(function (e) {
e.stopPropagation();
$(this).next().show();
})
$(document).click(function () {
$("#popup1,#popup2").hide();
})
DEMO
$(document).ready(function () {
$("#linkbutton_id").click(function () {
alert("The paragraph was clicked.");
if($("#image").hide())
{
$("#image").show();
return false;
}
});
});
$(document).ready(function () {
$("#div_id").click(function(){
$("#image").hide();
});
});
Code plus output link
https://jsfiddle.net/umxrn0Lg/2/
fullscreen output link
https://jsfiddle.net/umxrn0Lg/3/embedded/result/