I am using this code to auto submit the form
document.getElementById("file").onchange = function() {
document.getElementById("form").submit();
};
the form contain an image file input, once the image is selected the function is called, and this function creates an image that is inserted to display as follow:
document.getElementById("uploadImage").onchange = function() {
var oFile = document.getElementById("uploadImage").files[0];
if (document.getElementById("uploadImage").files.length === 0) {
return;
}
var img = document.createElement("img");
img.width = 200;
img.height = 200;
img.id = randomid;
img.src = "./upload/Images/" + oFile.name;//i want to point to the file uploaded
img.onload = function() {
document.getElementById(container).appendChild(img);
}
document.getElementById("form").submit();
};
the above code is working but it is continuously updating the image. Is there another way to approach this issue?
I believe you should you promise or something like that. once you get the response from
the below function then only you should call the submit ().
img.onload = function() {
document.getElementById(container).appendChild(img);
}
May be this link will help you to understand event life cycle hook
Related
I have the following code that I have written in Javascript:
function newImage(name) {
img = new Image();
img.onload = function () {
loaded++;
console.log("Loading: " + Math.round(loaded / 6 * 100) + "% complete");
};
img.src = "./assets/" + name;
return img;
}
var img1 = newImage("img1");
var img2 = newImage("img2");
var img3 = newImage("img3");
I want to know if the image that starts loading in the img variable stays loaded when it is returned to the img1 variable. As in, it will not re-run the onload function.
The answer is the image won't be downloaded again.
Here's a fiddle you can use to see that:
https://jsfiddle.net/uglynakedguy/eu4okzpx/7/
function newImage(name) {
img = new Image();
img.onload = function () {
loaded++;
console.log("Loading: " + Math.round(loaded / 6 * 100) + "% complete");
};
img.src = "https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500";
return img;
}
var imageLoaded = newImage("img1");
document.addEventListener('click', function (event) {
if (!event.target.matches('.add')) return;
document.body.appendChild(imageLoaded);
}, false);
If you check the JS, it has your function. First thing we do when page loads is getting the image. Then, when you click on the button, we inject your image in the page.
You will see that if the image has been loaded, when we inject it, it renders SUPER FAST, it is not downloaded again. You can prove that in network tab too, it will be listed once.
I need an image to change when it's clicked and to load a URL without anything visual changing on the page. I only need a total of two images and each image will be associated with one URL. I was able to replicate the example of onclick image change located at:
http://www.paulgriffiths.net/program/javascript/otherbasic1.php
For example: I want the image of the earth to change to mars and load URL #1. Then when mars is clicked on I want it to load back the picture of earth and load URL #2. I want the URL to load in the background and not change the images of earth and mars.
What do I add to the ".js" file below to accomplish this?
var newsrc = "mars.jpg";
function changeImage() {
if ( newsrc == "mars.jpg" ) {
document.images["pic"].src = "/images/program/js/forms/mars.jpg";
document.images["pic"].alt = "Mars";
newsrc = "earth.jpg";
}
else {
document.images["pic"].src = "/images/program/js/forms/earth.jpg";
document.images["pic"].alt = "Earth";
newsrc = "mars.jpg";
}
}
I used a boolean instead of testing strings but this should help you.
function loadCommand(url) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// if successfull
} else {
// if not successfull
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
var isOn = false;
var img = document.getElementById("pic");
// change handler
var loadImage = function() {
if (isOn) {
loadCommand("http://x.x.x.x/cmd/DOFF");
img.src = "/images/program/js/forms/mars.jpg";
img.alt = "Mars";
} else {
loadCommand("http://x.x.x.x/cmd/DON");
img.src = "/images/program/js/forms/earth.jpg";
img.alt = "Earth";
}
};
// set up event handler
img.onclick = function() {
// potentially send window to new location with window.location=<host>/cmd/DOFF or something similar
// or just change state
isOn = !isOn;
loadImage();
};
// load initial image
loadImage();
I have been trying to make this simpel image toggle on click function work but I am not sure what is wrong. I have to use querySelector and addEventListener, also jquery is not allowed. Could anyone please help me figure this out?
document.querySelector(".imageClass").addEventListener("click", function () {
var img = this.src;
if(img.src == "/image/location1.png") {
img.src = "/image/location2.png";
} else {
img.src = "/image/location2.png";
}
});
I'm getting this error:
document.querySelector(...).addEventlistener is not a function(...)
Getting a property would most likely return an absolute URL, and you really want to make sure you check the attribute, not the property.
Also, you're accesing src twice, first by doing var img = this.src then by doing img.src
And your condition does the same thing in both cases
document.querySelector(".imageClass").addEventListener("click", function () {
var img = this;
var src = img.getAttribute('src');
if( src == "/image/location1.png" ) {
img.src = "/image/location2.png";
} else {
img.src = "/image/location1.png";
}
});
Recieve your event by passing it with your parameters. From there you can access the target element of the event and get its src attribute.
document.querySelector(".imageClass").addEventListener("click", function (e) {
var img = e.target;
if(img.src == "/image/location1.png") {
img.src = "/image/location2.png";
} else {
img.src = "/image/location2.png";
}
});
if (DataService.Validation(file)) {
//angularjs call to api controller
};
//DataService
Validation: function (file) {
var Url = URL.createObjectURL(file);
var img = new Image();
$(img).load(function () {
var imgwidth = this.width;
var imgheight = this.height;
if (imgheight > 400) {
viewModel.ErrorMessage = 'The Image height cannot be more then 400 px.';
return false;
}
});
img.src = Url;
if (file == null) {
viewModel.ErrorMessage = 'Please select a file to upload.';
return false;
}
if (viewModel.Name == null) {
viewModel.ErrorMessage = 'Name is a required field.';
return false;
}
return true;
}
The above validation function is completing the execution and returning true without the code inside img load function is checked..It means tht even if the image is greater then 400px the validation returns true as the code inside load runs after a long time once the whole Jquery ajax call is sent to api controller..
What I am trying to achieve is that the Validation should not return the value until the code inside the image load is executed.
I had same issue while checking dimension of image as image loading is asynchronous . Also as said by #Abhinandan
"IMG load function will execute only after your image is completely loaded by the browser and since its asynchronous your function will not wait for it to execute"
I used following approach. Hope it will help.
Set one extra attribute in image tag while on change of file like below
$('input[type=file]').on('change',function(){
element = $(this);
var files = this.files;
var _URL = window.URL || window.webkitURL;
var image, file;
image = new Image();
image.src = _URL.createObjectURL(files[0]);
image.onload = function() {
element.attr('uploadWidth',this.width);
element.attr('uploadHeigth',this.width);
}
});
and now you can modify your function to below
$.validator.addMethod('checkDim', function (value, element, param) {
var image = new Image();
var file = element.files[0];
var _URL = window.URL || window.webkitURL;
image.src = _URL.createObjectURL(file);
if(element.uploadWidth== param[0] element.uploadHeigth== param[1]){
return true;
}
else{
return false;
}
}, 'Image dimension must be as specified');
It work for me
The behaviour is correct as your function will return with 'true' value always.
IMG load function will execute only after your image is completely loaded by the browser and since its asynchronous your function will not wait for it to execute.
Also if you want to check the width/height of image being loaded, use naturalWidth/naturalHeight as this will give the right values and not the one assigned to the image by css.
What you can do is inside image-load function,you can call your function with true/false value as parameter.
I'm having an issue with getting the dimensions of a newly updated image element.
I'm using FileReader to display a preview of an image file on screen.
Once the filereader and associated code has finished executing, I retrieve the new dimensions of the image element so I can adjust them accordingly.
On some browsers, the info doesn't get updated straight away and I need to include a delay before I can retrieve the new dimensions. This results in the new image being resized according to the previous image's dimensions, and not its own.
How can I be sure the new image has been fully loaded?
I would have thought FileReader().onloadend would have been sufficient but apparently not. I think this is executed once the fileReader has loaded it, not when the DOM has rendered it. (Am I right?)
Then I found this question, which suggests using a timeout of 1 millisecond. This works sometimes, but not always. It seems to be down to the speed the browser is rendering the image (more-so available resources rather than filesize). Do we have no other way of detecting a change in these parameters?
HTML
<img src="#.png" alt=""/>
<input id="fileInput" type="file" accept='image/*' onChange="loadIt()" />
JS
preview = getElementsByTagName('img')[0];
function loadIt() {
var imgReader = new FileReader();
imgReader.readAsDataURL(document.getElementById('fileInput').files[0]); //read from file input
imgReader.onloadstart = function(e) {
//
}
imgReader.onload = function (imgReaderEvent) {
if (isImage()) {
preview.src = imgReaderEvent.target.result;
//
}
else {
preview.src = 'error.png';
//
}
}
imgReader.onloadend = function(e) {
setImage();
setTimeout(function(){
setImage();
}, 1);
setTimeout(function(){
setImage();
}, 2000);
//
}
};
function setImage() {
preview_w = preview.width;
preview_h = preview.height;
console.log('dimensions: '+avatar_preview_w+' x '+avatar_preview_h);
//
};
You should call preview.onload or preview.onloadend on your image to detect that it has finished loading. You're also calling your events after you readAsDataURL The code should look like this
var preview=document.getElementsByTagName("img")[0];
function loadIt() {
var imgReader=new FileReader();
imgReader.onload=function(){
if (isImage()) {
preview.src = imgReader.result;
preview.onload=setImage;
} else {
preview.src = 'error.png';
//
}
imgReader.readAsDataURL(document.getElementById('fileInput').files[0]); //read from file input
}
function setImage(){
preview_w = preview.width;
preview_h = preview.height;
console.log('dimensions: '+avatar_preview_w+' x '+avatar_preview_h);
}
You're calling imgReader.readAsDataURL before your .onload and .onloadend is set.
I do not know what some of the variables are with-in the body of your setImage();however, start here:
function loadIt() {
var preview = getElementsByTagName('img')[0],
setImage = function () {
preview_w = preview.width;
preview_h = preview.height;
console.log('dimensions: '+avatar_preview_w+' x '+avatar_preview_h);
},
imgReader = new FileReader();
imgReader.onloadstart = function(e) {};
imgReader.onload = function (imgReaderEvent) {
if (isImage()) {
preview.src = imgReaderEvent.target.result;
}
else {
preview.src = 'error.png';
};
};
imgReader.onloadend = function(e) {setImage();};
imgReader.readAsDataURL(document.getElementById('fileInput').files[0]); //read from file input
};