Javascript- code getting executed before all elements are ready - javascript

I have this code in my web. This page takes multiple image files as input and displays them before uploading them to server.
<html>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
<body>
<header>
<h1>File API - FileReader</h1>
</header>
<label for="files">Select multiple files: </label>
<input id="files" type="file" multiple/>
<div id='10' style=" width:100px; height:50px; background-color:#006633" onclick="submit_rr(event)">Click</div>
<output id="result" />
</body>
<script language="javascript" type="text/javascript" >
function submit_rr(event){
$('#files').click();
}
$("#files").change(function(){
show_selected(this);
});
function show_selected(input){
for(i = 0;i< input.files.length; i++) {
var reader = new FileReader();
reader.readAsDataURL(input.files[i]);
reader.onload = function (e) {
var img = new Image;
img.onload = function() {
if(img.width>=img.height){
ratio=img.height/img.width;
height=ratio*100;
height_rem=(100-height)/2;
var crt=document.createElement('div');
crt.id="main_some";
crt.className="ind_req_sty";
var Friend="Friend";
crt.innerHTML="<img id="+i+" width='100px' height='"+height+"px' src='"+e.target.result+"'/>";
document.getElementById('10').appendChild(crt);
}else{
ratio=img.width/img.height;
width=ratio*100;
var crt=document.createElement('div');
crt.id='main_req';
crt.className="ind_req_sty";
crt.innerHTML="<img id="+i+" height='100px' width='"+width+"' src='" + e.target.result +"'/>";
document.getElementById('10').appendChild(crt);
}
}
img.src=reader.result;
}
}
}
</script>
</html>
Problem is that, this script executes before all the elements are displayed. As a result only few images are displayed(say 4 out of 10 selected). I tried adding .ready() and .load() but that doesn't work. However if I add an alert('something') all images are displayed without any issue. is there a way I can delay execution so that all images are loaded. I have also tried setTimeout() without any luck. Thanks for your help

If you properly indent your code, you will set that $("#files).change(/*..*/) line is not inside the submit_rr function.
Wrap all your code with
$(function () {
/* your code here */
});
Basically what it does is, creating event handler on dom ready event and after that we are executing our script.
Also, this is a commonly asked question. If you believe the problem you are having is not unique to your case, do your research, if you still cannot find the answer, go ahead and ask.
The link at http://whathaveyoutried.com tells about developers' feelings on answering a repeatedly asked question.

Try putting your <script> tag before the closing </body> tag

Hi After searching .....
I found this works ...
function eecute(event){
var files = event.target.files; //FileList object
var output = document.getElementById("result");
for(var i = 0; i< files.length; i++)
{
var file = files[i];
//Only pics
if(!file.type.match('image'))
continue;
var upload_pic = new FileReader();
upload_pic.addEventListener("load",function(event){
var pic_u = event.target;
var img = new Image;
img.src=pic_u.result;
if(img.width>=img.height){
var div = document.createElement("cover");
div.innerHTML= "<div style='text-align: center; margin-top:8px; width:150px;margin-right:5px; height:150px;float:left'><img style='display:inline-block;' width='150' src='" + pic_u.result + "'/></div>";
output.insertBefore(div,null);
}else{
var div = document.createElement("cover");
div.innerHTML="<div style='text-align: center ;margin-top:8px;width:150px; margin-right:5px; height:150px;float:left'><img style='display:inline-block; margin:auto;' src='" + pic_u.result + "'height='150' /></div>";
output.insertBefore(div,null);
}
});
//Read the image
upload_pic.readAsDataURL(file);
}
}

Related

Newline Break when saving innerHTML to text file I automatically get a newline Break in the saved Text file or when reload the page

The result in the text file is always saving the file with a linebreak not just the p tag in div1 when clicking the button.
example:
<p>x1</p>
....linebreak
If I click the button 3 time and reload the page and click the button again I get this as well.
<p>x1</p><p>x2</p><p>x3</p>
<p>x1</p>
html code:
<button id="btn" value="" onclick="btn();return false"style="margin:1px"> Write to file </button>
<div id="div1" style="width:200px; border:1px; margin:5px 0px;"></div>
Javascript code:
// Read or Write to file
var path = 'c:\\home\\lab.txt';
var num = 0 ;
var myDiv = document.getElementById('div1');
// Read or Write to file
var path = 'c:\\home\\lab.txt';
var num = 0 ;
var myDiv = document.getElementById('div1');
myDiv.innerHTML = readFileInIE(path);
function readFileInIE(path) {//Read file content
try {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var file = fso.OpenTextFile(filePath, 1);
var rfileContent = file.ReadAll();
file.Close();
return rfileContent;
} catch (err) {
alert('Unable to access local files or location. '+ err);
return "";
//}
}
function btn(){ //onClick Calls writeFileInIE and paragraph to file on new line.
num++;
var myInput= "P" + num.toString();
var myPara = '<p>' + myInput + '</p>';
myDiv.innerHTML = myDiv.innerHTML + MyPara;
writeFileInIE(path, myDiv.innerHTML);
}
function writeFileInIE(filePath, fileContent) { //Write to file function
try {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var file = fso.OpenTextFile(filePath, 2, true);
file.WriteLine(fileContent);
file.Close();
return fileContent;
} catch (err) {
alert('Unable to access local files or location.');
file.Close();
}
}
My goal is to be able to write to the file only the innerHTML from the div1 element innerHTML to the text only content in this format.
example in exact format I want even on a reload to the text file :
<p>x1</p>
<p>x2</p>
<p>x3</p>
<p>x1</p>
<p>x2</p>
Can't test your code but i see you comment and ending } , probably that is messing with your code.
//} after the return you should uncomment
function readFileInIE(path) {//Read file content
try {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var file = fso.OpenTextFile(filePath, 1);
var rfileContent = file.ReadAll();
file.Close();
return rfileContent;
} catch (err) {
alert('Unable to access local files or location. '+ err);
return "";
//}
}
After that, try put a <br> maybe it will do that break you want
var myPara = '<p>' + myInput + '</p><br/>';
Ok many be with this you will see what I mean by not getting the correct format and it keeps adding a line break to the file c:\lab.txt. It works fine the with the button.
Until I reload the page or refresh it I get a newline Break so I end up with this
<p>P1</p>
<p>P2</p>
<p>P1</p>
<p>P1</p>
<p>P2</p>
<p>P3</p>
I want it to do this:
<p>P1</p>
<p>P2</p>
<p>P1</p>
<p>P3</p>
<p>P1</p>
<p>P2</p>
<p>P3</p>
I want it to allways save the file with out blank line breaks between the P tags.
It fine if I star with a blank document but once it reloads with data in the text file.
I will get a new linebreak saves in the middle.
Try to use the new code I have posted.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test Page OPEN</title>
<Script language="JavaScript">//*/alert("helloWorld".toUpperCase())
</Script>
</head>
<body>
<h5> "Lab.txt file populating div1.innerHTML that is being changed via JavaScript while being save to Lab.txt"</h5>
<div id="div1" style="width:600px; height:150px; border:1px dotted; margin:5px 0px; overflow: scroll;"></div>
<table>
</tr>
<tr>
<td><button id="btn1" value="" onclick="btnWrite();return false"> Write to file </button></td>
<td><button id="btn2" value="" onclick="btnRead() ;return false"> Read from file</button></td>
</tr>
<tr>
<td>Content Sent to file</td>
<td>File Content</td>
</tr>
<tr><td><pre id="pre1" style='border:1px solid red ; width:300px; height: 300px; overflow: scroll;'></pre>1</td>
<td><pre id="pre2" style='border:1px solid blue; width:300px; height: 300px; overflow: scroll;'></pre>2</td>
</table>
<div id="lastDiv"></div>
<Script language="JavaScript">//*/alert("helloWorld".toUpperCase())
var lDiv = document.getElementById('lastDiv')
// Read or Write to file
var path = 'c:\\home\\lab.txt'; // Change to any location will create the file.
var num = 0 ;
var myDiv = document.getElementById('div1');
myDiv.innerHTML = readFileInIE(path);
function btnRead(){ //onClick Calls writeFileInIE and paragraph to file on new line.
document.getElementById('pre2').innerText = readFileInIE(path);
//document.getElementById("pre2").innerText = "hello";
}
function readFileInIE(readPath) {//Read file content
try {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var file = fso.OpenTextFile(readPath, 1);
var readFileContent = file.ReadAll();
file.Close();
return readFileContent;
} catch (err) {
tkr("Error on reading: "+ path + " - " + err);//alert('Unable to access local files or location. '+ err);
return "";
}
}
function btnWrite(){ //onClick Calls writeFileInIE and paragraph to file on new line.
num++;
var myCode =""
var myInput= "P" + num.toString();
var myPara = '<p>' + myInput + '</p>'+'\n';
myDiv.innerHTML = myDiv.innerHTML + myPara;
document.getElementById('pre1').innerText = writeFileInIE(path, myDiv.innerHTML);
document.getElementById('pre2').innerText = readFileInIE(path);
}
function writeFileInIE(filePath, wFileContent) { //Write to file function
try {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var file = fso.OpenTextFile(filePath, 2, true);
file.WriteLine(wFileContent);
file.Close();
return wFileContent;
} catch (err) {
tkr("Error on write file: "+ path + " - "+ err);//alert('Unable to access local files or location.');
file.Close();
return err;
}
}
//*/
// track locations and find errors debug
function tkr(myData){lDiv.innerHTML = lDiv.innerHTML + "<p>" + myData + "</p>";}
tkr("JavaScript complete onload");
</Script>
</body>
</html>

Why won't my program display the .png it receives from the user as a form input?

I have a program that uses a form to receive a .png file from the user, which is then dynamically set as an img. The form seems to allow me to select a file, but does not display that file. I was under the assumption that I could set the src for the img as the variable(wscimginput) associated with the user's file, but that does not seem to be working? Is there another way I should approach this?
Here's the piece of code dealing with the form and the image.
var wscimgform = document.createElement("form");
var wscimginput = document.createElement("input");
wscimgform.appendChild(wscimginput);
_wsc.appendChild(wscimgform);
wscimginput.setAttribute("id", "wscimginput");
wscimginput.setAttribute("type", "file");
wscimginput.setAttribute("accept", "image/*");
var wscimg = document.createElement("img");
_wsc.appendChild(wscimg);
wscimg.setAttribute("src", "wscimginput");
wscimg.setAttribute("position", "absolute");
wscimg.setAttribute("height", "80%");
wscimg.setAttribute("top", "20%");
This is adapted from the linked article without jQuery.
<html>
<head>
</head>
<body>
<div id="formDiv">
</div>
<script type="text/javascript">
var f = document.createElement("form");
var fi = document.createElement("input");
fi.setAttribute("id", "daFile");
fi.setAttribute("type", "file");
fi.setAttribute("accept", "image/*");
fi.addEventListener("change", showPreview);
f.appendChild(fi);
var i = document.createElement("img");
i.setAttribute("id", "daImg");
i.setAttribute("width", "200px");
i.setAttribute("height", "200px");
f.appendChild(i);
document.getElementById("formDiv").appendChild(f);
function showPreview(ev) {
if (ev.target.files && ev.target.files[0]) {
var r = new FileReader();
r.onload = function (e) {
document.getElementById("daImg").setAttribute("src", e.target.result);
}
r.readAsDataURL(ev.target.files[0]);
}
}
</script>
</body>
</html>

add image as div with javascript

I am trying to add an image as an element into my webpage. I am unable to do so. There are instructions on how to preview an image, but I was unable to find a solution.
What I want it to do is to add a div with an image into the webpage and keep loading it with different images. So after I add image 1, I would load image 2 under image 1 in the same webpage.
html body code:
<input type='file' id='getval' /><br/><br/>
<span onclick="readURL()" class="addBtn">Add</span>
<div id="myUL"></div>
javascript code:
<script type="text/javascript">
// grabs image
var file = document.createElement('image');
file.src = document.getElementById('getval').files[0];
// creates div & assigns id
var div = document.createElement('div');
div.id = 'item';
// adds file to div
file.type = 'image';
div.appendChild(file);
//adds item
document.getElementById("myUL").appendChild(div);
}
</script>
edit1*
I think adding the output of the code I want to display would be better inside the html document.
javascript generates html code inside document:
<div style="background-image":url("image");"><div>
You can use this script
count = 0;
function viewImage(){
var imagefile = document.querySelector('#image');
if (imagefile.files && imagefile.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
var content = '<img id="temp_image_'+count+'" style="border: 1px solid; width: 107px;height:107px;" >';
document.querySelector('#all_images').innerHTML += content;
document.querySelector('#temp_image_'+count).setAttribute('src', e.target.result);
}; reader.readAsDataURL(imagefile.files[0]);
this.imagefile = imagefile.files[0];
count++;
}else{
console.log("Image not selected");
}
}
<div id="all_images">
</div>
<input id="image" name="image" type="file" onChange="viewImage()">
Here you go, although pay attention to the comment at line 3.
<script type="text/javascript">
var file = document.createElement("img");
file.setAttribute("src", document.getElementById('getval').files[0]); //You can use HTML5 File API here
file.setAttribute("height", "250");
file.setAttribute("width", "250");
var divTocreate = document.createElement('div');
divTocreate.id = 'item';
divTocreate.appendChild(file);
document.getElementById("myUL").appendChild(divTocreate);
</script>

Unable to read data from multiple files using HTML FileReader

<input type="file" id="input" multiple onchange="handleFiles(event.target)">
<script language="javascript" type="text/javascript">
<!--
function handleFiles(input)
{
for (i = 0; i < input.files.length; i++)
{
var reader = new FileReader();
reader.onload = function()
{
alert(reader.result)
};
reader.readAsText(input.files[i]);
}
}
//-->
</script>
I am trying to display the contents of some files that I upload. It works fine if I select a single file, but if I select multiple files, only the content of one file is displayed, rest all are blank. What am I doing wrong?
You just need to amend it slighty to do the following:
<input type="file" id="input" multiple onchange="handleFiles(event.target)">
<script language="javascript" type="text/javascript">
function handleFiles(input)
{
for (var i = 0; i < input.files.length; i++) { //for multiple files
(function(file) {
var name = file.name;
var reader = new FileReader();
reader.onload = function(e) {
// get file content
var text = e.target.result;
alert(text)
}
reader.readAsText(file, "UTF-8");
})(input.files[i]);
}
}
</script>
Reference: https://stackoverflow.com/a/9815648/3088780
I think jquery help you easily
HTML:
<script src="jquery-2.2.0.min.js"></script>
<input type="file" multiple="multiple" />
<ul id="output">
</ul>
Jquery:
$('input:file[multiple]').change(
function(e){
console.log(e.currentTarget.files);
var numFiles = e.currentTarget.files.length;
for (i=0;i<numFiles;i++){
fileSize = parseInt(e.currentTarget.files[i].size, 10)/1024;
filesize = Math.round(fileSize);
$('<li />').text(e.currentTarget.files[i].name).appendTo($('#output'));
$('<span />').addClass('filesize').text('(' + filesize + 'kb)').appendTo($('#output li:last'));
}
});
reference from : https://stackoverflow.com/a/7719334/5566169

How do you read a local file on your PC and update it constantly in javascript?

So, I've made a java program that runs through a list of IPs, pings them, and updates a file on the devices status. I want to know how to open the file into a webpage and update it, so a user can open the webpage and just see a list of data from the file, they don't have to select the file or refresh the page.
Is this feasible to do with javascript/html?
This is the code I'm working with so far:
<html>
<head>
<title>Import Data</title>
<script>
var openFile = function() {
var input = event.target;
var reader = new FileReader();
reader.onload = function() {
var text = reader.result;
var node = document.getElementById('output');
node.innerText = text;
console.log(reader.result.substring(0,200));
};
reader.readAsText(input.files[0]);
setTimeout(openFile(),1000);
};
</script>
</head>
<body>
<input type='file' accept='text/plain' onchange='openFile()'><br>
<div id='output'>
</body>
</html>
But I can't seem to hunt down where to hardcode the path to the file in. When I use this manual selection method, it'll update once, whether the file increases in elements or decreases.
EDIT:
I've narrowed it down to where the file needs to be uploaded:
<html>
<head>
<title></title>
<script>
function uploadFile() {
var reader = new FileReader();
reader.onload = function(event) {
var contents = event.target.result;
console.log("File contents: " + contents);
};
reader.onerror = function(event) {
console.error("File could not be read! Code: " + event.target.error.code);
};
var fileInputElement = document.getElementById("FileName");
reader.readAsText(fileInputElement.files[0]);
console.log(fileInputElement.files[0]);
}
</script>
</head>
<body>
<input type='file' accept='text/plain' value='RESULTS.txt' id='FileName' onchange='uploadFile()' style="display:none;">
</body>
</html>
If I try to type just a file path in a string, it complains it's not type 'blob'. When I do this, it requires the user to enter a file name, but obviously it can't be seen. How can I make that 'file' variable a static variable so it always opens a that file without prompting the user?
Doing some more research, it's security reasons as to why you can't access a file from the local computer.
So, in lieu of all that, I made some code that will constantly load the selected file so you can see whenever it changes:
<html>
<head>
<title>Import Data</title>
<script>
var input;
var openFile = function() {
var reader = new FileReader(event);
reader.onload = function() {
var text = reader.result;
var node = document.getElementById('output');
node.innerText = text;
console.log(reader.result.substring(0,200));
};
reader.readAsText(input.files[0]);
setTimeout(openFile,1000);
};
</script>
</head>
<body>
<input type='file' accept='text/plain' onchange='input = event.target; openFile(event);'><br>
<div id='output'>
</body>
</html>

Categories

Resources