I am trying to create some code to work. However, I keep getting errors, and I have been stuck with this for a while now and in need of help. Whenever the image gets an attempt to be added to the page, I get:
<undefined src='(this is where the filepath is listed)'><undefined>
Why are the tags not coming out as div?
Css Code:
.clock{
background-image:url('');
background-size:cover;
background-position: center;
height: 250px; width: 250px;
border: 1px solid #bbb;
}
#myUL{
height: 1000px;
width: 1000px;
}
Html Code:
<input type='file' id='getval' />
<span onclick="readURL()" class="addBtn">Add</span>
<div class='clock'></div>
<div id='myUL'></div>
Script code:
function readURL(){
var file = document.getElementById("getval").files[0];
var reader = new FileReader();
reader.onloadend = function(){
var div = document.createElement(div);
div.setAttribute("src", "url(" + reader.result + ")");
div.class = 'clock';
document.getElementById('myUL').appendChild(div);
}
if(file){
reader.readAsDataURL(file);
}else{}
}
var div = document.createElement(div); // <<< (div) is a variant.
see https://jsfiddle.net/3L53bzx5/1/
reader.onloadend = function() {
var img = document.createElement('img');
img.setAttribute("src", reader.result);
img.className = 'clock';
document.getElementById('myUL').appendChild(img);
}
You have to change below line
var div = document.createElement(div);
to
var div = document.createElement('div');
in your readURL() method.
Related
I set multiple image sources for a div using javascript function. I want that when user clicks to the button then only a specific image set to that div.
function changeColor1() {
document.getElementById("myDIV").style = "background-image:url(coloredshirtsimages/coloredwithoutsleeve/red_withoutsleeve.png)"
document.getElementById("myDIV").style = "background-image:url(coloredshirtsimages/coloredhalfsleeveroundneck/red_halfsleeve.png)"
document.getElementById("myDIV").style = "background-image:url(coloredshirtsimages/coloredfullhalf/red_fullhalfsleeve.png)"
document.getElementById("myDIV").style = "background-image:url(coloredshirtsimages/coloredfullsleeve/red_fullsleeve.png)"
document.getElementById("myDIV").style = "background-image:url(coloredshirtsimages/coloredfullsleevev-neck/red_fullsleevevneck.png)"
document.getElementById("myDIV").style = "background-image:url(coloredshirtsimages/coloredshirtsimages/coloredvneck/red_vneck.png)"
}
<div id="myDIV"></div>
<button style="background-color:red;outline:none" class="colors" onclick="changeColor1()"></button>
#myDIV {
width: 550px;
height: 650px;
background-image: url(coloredshirtsimages/coloredhalfsleeveroundneck/white_halfsleeve.png);
border: 2px solid black;
color: orange;
float: right;
margin-top: 200px;
background-repeat: no-repeat;
}
I changed the image using css and javascript now the image belongs to particular category for example(white_vneck)is goes to div but problem is that only one image was gone to div. I want that other image (red_vneck.png) goes to div when i clicked the button in place of white_vneck.
Please feel free to ask a question if you have any confusion
Pass a parameter to your function to help it understand which image you wish to display:
onclick="changeColor1('abc.png')"
function changeColor1(pic) {
document.getElementById("myDIV").style = "background-image:url(" + pic + ")";
}
According your code snippet:
function changeColor1(pngName) {
document.getElementById("myDIV").style = "background-image:url("+pngName+")";
}
<div id="myDIV"></div>
<button style="background-color:red;outline:none" class="colors" onclick="changeColor1('coloredshirtsimages/coloredwithoutsleeve/red_withoutsleeve.png')"></button>
For selecting random image:
onclick="changeColor1()"
var pics =[
'coloredwithoutsleeve/red_withoutsleeve.png' ,
'coloredhalfsleeveroundneck/red_halfsleeve.png',
'coloredfullhalf/red_fullhalfsleeve.png',
'coloredfullsleeve/red_fullsleeve.png',
'coloredfullsleevev-neck/red_fullsleevevneck.png',
'coloredshirtsimages/coloredvneck/red_vneck.png'
];
function changeColor1() {
//random selection of pic
var picIndex = Math.floor(Math.random() * pics.length);
document.getElementById("myDIV").style = "background-image:url(coloredshirtsimages/" + pics[picIndex] + ")";
}
I am trying too add image inside dynamically created div. When user create go button it should create div element and image inside it according to value selected in select box. I have created div tag dynamically and created image object in order to get image. but in my code image is not loading inside div. can anyone help me to figure out issue ?
CSS
<style>
body{
background-image: url("final_images/back.jpg");
}
.container{
/*width: 600px;*/
/*height: 200px;*/
border:inset;
margin-top: 100px;
margin-left: 300px;
margin-right: 190px;
background-color:rgba(255, 234, 134, 0.9);
}
#selectBox{
margin-left: 210px;
width: 160px;
}
#holder {
width: 300px;
height: 300px;
background-color: #ffffff;
}
</style>
HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class = 'container' id="main">
<form name="myForm">
<select name="mySelect" id="selectBox">
<option value="womens">Women's coat</option>
<option value="mens">Men's coat</option>
<option value="kids">Kid's toys</option>
<option value="mixture">Classic mixture</option>
<option value="earing">Gold Earing</option>
</select>
<INPUT TYPE="button" VALUE="Go" id="go">
</INPUT>
</form>
<HR size="4" color="red" id="hr">
<!-- <div id="holder"> </div> -->
</div>
</body>
</html>
Javascript
<script>
imageObj = new Image(128, 128);
// set image list
images = new Array();
images[0]="final_images/wcoat.jpg";
images[1]="final_images/wcoat.jpg";
var go = document.getElementById('go');
go.addEventListener("click", loadItem);
function loadItem() {
var mainDiv = document.getElementById("main");
var btnPre = document.createElement("input");
//Assign different attributes to the element.
btnPre.type = "button";
btnPre.value = "previous";
btnPre.id = "preBtn";
mainDiv.appendChild(btnPre);
newdiv = document.createElement('div'); //create a div
newdiv.id = 'holder';
mainDiv.appendChild(newdiv); //add an id
var btnNxt = document.createElement("input");
//Assign different attributes to the element.
btnNxt.type = "button";
btnNxt.value = "next";
btnNxt.id = "nxtBtn";
mainDiv.appendChild(btnNxt);
var holder = document.getElementById("holder");
if(document.getElementById('selectBox').value == "womens"){
holder.src = images[0] + " Women's coat";
}
else if(document.getElementById('selectBox').value == "mens"){
holder.src = images[1] + " Men's coat";
}
}
</script>
A div is not an image container. Replace with img in the createElement fixes this.
Another big problem is the margins you use.
I've made a few adjustments
replaced margin-left with float: right for the select
put margin auto for left and right on the box.
imageObj = new Image(128, 128);
// set image list
images = new Array();
images[0] = "final_images/wcoat.jpg";
images[1] = "final_images/wcoat.jpg";
var go = document.getElementById('go');
go.addEventListener("click", loadItem);
function loadItem() {
var mainDiv = document.getElementById("main");
var btnPre = document.createElement("input");
//Assign different attributes to the element.
btnPre.type = "button";
btnPre.value = "previous";
btnPre.id = "preBtn";
mainDiv.appendChild(btnPre);
newdiv = document.createElement('img'); //create a div
newdiv.id = 'holder';
mainDiv.appendChild(newdiv); //add an id
var btnNxt = document.createElement("input");
//Assign different attributes to the element.
btnNxt.type = "button";
btnNxt.value = "next";
btnNxt.id = "nxtBtn";
mainDiv.appendChild(btnNxt);
var holder = document.getElementById("holder");
if (document.getElementById('selectBox').value == "womens") {
holder.src = images[0] + " Women's coat";
} else if (document.getElementById('selectBox').value == "mens") {
holder.src = images[1] + " Men's coat";
}
}
body {
background-image: url("final_images/back.jpg");
}
* {
box-sizing: border-box;
}
.container {
width: 400px;
border: inset;
margin-top: 100px;
margin-left: auto;
margin-right: auto;
background-color: rgba(255, 234, 134, 0.9);
}
#selectBox {
float: right;
width: 160px;
}
#holder {
width: 300px;
height: 300px;
background-color: #ffffff;
}
<div class='container' id="main">
<form name="myForm">
<select name="mySelect" id="selectBox">
<option value="womens">Women's coat</option>
<option value="mens">Men's coat</option>
<option value="kids">Kid's toys</option>
<option value="mixture">Classic mixture</option>
<option value="earing">Gold Earing</option>
</select>
<INPUT TYPE="button" VALUE="Go" id="go">
</INPUT>
</form>
<HR size="4" color="red" id="hr" />
<!-- <div id="holder"> </div> -->
</div>
You need to use an image tag instead of a div. You could also load images with CSS but thats probably not what you want.
starting on this line:
var holder = document.getElementById("holder");
var image = new Image(128, 128);
if (document.getElementById('selectBox').value == "womens") {
image.src = images[0];
holder.appendChild(image);
holder.appendChild(document.createTextNode(" Women's coat"));
} else if (document.getElementById('selectBox').value == "mens") {
image.src = images[1];
holder.appendChild(image);
holder.appendChild(document.createTextNode(" Men's coat"));
}
Let me elaborate.
In the JavaScript code you are creating a div element here
newdiv = document.createElement('div'); //create a div
newdiv.id = 'holder';
mainDiv.appendChild(newdiv);
and then you are searching for element with Id holder and setting new image url.
var holder = document.getElementById("holder");
// holder is <div></div> element
if (document.getElementById('selectBox').value == "womens") {
holder.src = images[0] + " Women's coat";
} else if (document.getElementById('selectBox').value == "mens") {
holder.src = images[1] + " Men's coat";
}
holder is a div tag now. it has no src attribute
But div element do not have attribute with name src. so the above code will just add one more attribute to your div tag. but browser will not interpret it.
So if you want load image by setting src attribute, then you probably have to create holder as img tag which has attribute src. like this.
newdiv = document.createElement('img'); //create a img
newdiv.id = 'holder';
mainDiv.appendChild(newdiv);
holder is a img tag. now it has src attribute
now it will work with no problem.
I want to upload an image by clicking on the image element with id='IBrowse' but an error occurs when I click on the that image.
Cannot read property 'target' of undefined(…) (in Chrome)
TypeError: event is undefined (in Firefox)
<div class="col-md-12 col-sm-12 col-xs-12 form-group has-feedback pull-right bordered">
<img id="HImg" src="~/b/b.jpg" style="height: 120px; max-width: 100%; width: 280px; position:relative", class="img-responsive" />
<img id="IBrowse" src="~/a/a.png" style="position: absolute; width: 20%; top: 5%; left: 17%;" />
#Html.TextBoxFor(m => m.Img, new { #class = "form-control has-feedback-left file btntag", style = "display: none;", #onchange = "open(e)", #type = "file", placeholder = "Upload Image" })
#Html.ValidationMessageFor(m => m.Img, "", new { #class = "text-danger" })
</div>
$(function () {
$('#IBrowse').on('click', function () {
$('#Img').trigger('onchange');
});
});
onchange event code
<script>
var IsUpdate = false;
var open = function (event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function () {
var dataURL = reader.result;
var output = document.getElementById('ImgHTMLElement');
output.src = dataURL;
};
reader.readAsDataURL(input.files[0]);
};
</script>
Also, the CSS is not working:
#IBrowse:hover {
width: 23%;
}
I never use onchange so maybe there is a way to do this there. However, I would simply drop the onchange="....." and use a handler like this:
<script>
var IsUpdate = false;
$('#Img').on('change', function(event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function() {
var dataURL = reader.result;
var output = document.getElementById('ImgHTMLElement');
output.src = dataURL;
};
reader.readAsDataURL(input.files[0]);
});
</script>
As for your css issue, the problem is that you define an inline style like:
<img id="HImg" src="~/b/b.jpg" style="height: 120px; max-width: 100%; width: 280px; position:relative", class="img-responsive" />
The css rule #IBrowse:hover {width: 23%;} is applied, but it will not override the inline style setting which has a higher precedence. You can overcome that by
Option 1) Preferred method
Move your inline style to a css rule instead of inline like this:
#IBrowse{
position: absolute;
width: 20%;
top: 5%;
left: 17%;
}
#IBrowse:hover {
width: 23%;
}
jsFiddle example
Option 2)
Leave the inline style and add !important to the hover css rule like this:
#IBrowse:hover {
width: 23% !important;
}
jsFiddle example
I haven't tested your code but if you want your open function to be passed the event object you should specify it as event rather than e in the onchange attribute definition, since this is not an assignment to the the event itself, but a callback function body that already has been passed the event parameter:
#onchange = "open(event)"
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>
The HTML code for image file input:
<input type="file" autocomplete="off" name="background-image" accept="image/*" />
The destination div block where I want to dynamically set the background image:
<div class="clock"></div>
The jQuery function I'm currently using for setting image file uploaded as div background image:
$(".background>div>input[type=file]").change(function () {
var fileExtension = ['jpeg', 'jpg', 'png', 'gif', 'bmp'];
if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
alert("Only '.jpeg','.jpg', '.png', '.gif', '.bmp' formats are allowed.");
}
else {
$(".clock").css("background-image",'url("' + $(".background>div>input[type=file]").val() + '")');
}
});
The issue is that the background-image is not being set. This may possibly be because when I checked with browser inspector, the file upload is not containing file url.
Note: The background-color of .clock is set to white initially.Also I'd not like to use a server since my intention is to keep it as client side only application.
This may solve your problem
JS FIDDLE
HTML
<input type='file' id='getval' name="background-image" /><br/><br/>
<div id='clock'></div>
CSS
#clock{
background-image:url('');
background-size:cover;
background-position: center;
height: 250px; width: 250px;
border: 1px solid #bbb;
}
PURE JAVASCRIPT
document.getElementById('getval').addEventListener('change', readURL, true);
function readURL(){
var file = document.getElementById("getval").files[0];
var reader = new FileReader();
reader.onloadend = function(){
document.getElementById('clock').style.backgroundImage = "url(" + reader.result + ")";
}
if(file){
reader.readAsDataURL(file);
}else{
}
}
It's small way to do this without using FileReader.
http://jsfiddle.net/PuneetChawla/vqn7r0nj/
HTML
<input type='file' id='getval' name="background-image" onchange="readURL(event)" /><br/><br/>
<div id='clock'></div>
CSS
#clock{
background-image:url('');
background-size:cover;
background-position: center;
height: 250px; width: 250px;
border: 1px solid #bbb;
}
JavaScript
function readURL(event){
var getImagePath = URL.createObjectURL(event.target.files[0]);
$('#clock').css('background-image', 'url(' + getImagePath + ')');
}
Explanation - The URL.createObjectURL() static method creates a DOMString containing an URL representing the object given in parameter.
var loadFile = function(event) {
var output = document.getElementById('output');
output.style.backgroundImage= "url("+URL.createObjectURL(event.target.files[0])+")";
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<input type="file" accept="image/*" onchange="loadFile(event)">
<div style="width: 500px;height: 500px;" id="output"></div>
</body>
</html>