Detect image input loading - javascript

I was using this code:
<input type="image" ... onLoad="this.style.opacity = 1" />
It works fine in IE (at least, the versions that support opacity :p) but in Chrome the onLoad event did not fire when the image loaded.
Note that the src attribute of the input can change, and when it does some JavaScript sets the opacity to 0 first, and suitable transition properties make it look like the image fades out and the new one fades in. Also, use of <input type="image"> is required because the server needs the coordinates.
I have jerry-rigged it using an absolutely-positioned <img> taking the onLoad and opacity, placed behind the <input> that now uses a transparent GIF pixel. While it works, it's ugly.
Is there any way to detect the successful loading of an image used in an <input> in Chrome, or is this like background-image, undetectable?
EDIT: In case it helps, here's a Fiddle

This is sort of a hack, but you can instantiate a Javascript Image object, and then set the event listener on that and then set the src of the input when it's done loading:
http://jsfiddle.net/t8n4y/
Disclaimer: only tested on Chrome
HTML:
<input type="image" id="imgInput" />
Javascript:
var photo = document.getElementById('imgInput');
var img = new Image();
img.addEventListener('load', function () { alert("done loading"); }, false);
img.src = 'http://jeremydouglass.com/gamertextually/images/gt_snowflake_tags-2-ach-large.png?ran=' + Math.random();
photo.src = img.src;

I remember I ran into a problem like this in the past. You can detect it by doing the following:
window.onload = function(){
var input = document.getElementById('input1');
input.src='';
input.addEventListener('load', loadImage, false);
input.src = 'http://theoffguard.net/wp-content/upLoads/2012/04/Nick-Cage.jpg';
}
function loadImage()
{
console.log("Image is loaded");
}
DEMO:
http://jsbin.com/ufovom/9/edit
Hope this helps!

<input id="image" type="image" ... onLoad="this.style.opacity = 1" />
//script ->
$("#image").change(function () {
if (this.files && this.files[0]) {
var FR = new FileReader();
FR.onload = function (e) {
//your onload
};
FR.readAsDataURL(input.files[0]);
}
});

You can use the addEventListener() method with a reference of your input.
Notice that before add the event listener to the input you'll need to let the page to load, for do it, just apply another event listener for the window object and then fire your function that reference your input.

Related

Is it possible to change the image src of an image input by clicking on said image?

So I'm just messing around with HTML and Javascript and I was wondering how to make it so where a user clicks on an image and then that image changes after the click. At first I thought it would be a simple function call on a onclick like so:
HTML:
<input type="image" src="Images/img.png" id="img" onclick="imgChange()">
Javascript:
function imgChange()
{
var img = document.getElementById("img");
img.src="Images/img2.png";
}
but when executing it it doesn't seem to work. Any suggestions?
It works perfectly fine
function imgChange() {
var img = document.getElementById("img");
img.src="https://live.staticflickr.com/7166/6621290239_250dce025d_b.jpg";
}
<input type="image" src="https://live.staticflickr.com/7440/8838399307_9e9e9668f6_b.jpg" id="img" onclick="imgChange()">
You can also try moving the images to the same directory as the HTML file to make it simpler.
Your code works perfectly fine.
Check your image location maybe there is a problem.
And try adding a ./ before the address of the image ./ means the current directory
Check this here Html File Paths
like this :
function imgChange(){
var img = document.getElementById("img");
img.src = "./Images/img2.png";
}
And a better way to do this passing this in the function. Here this is the image whick will be clicked.
<input type="image" src="Images/img.png" onclick="imgChange(this)">
function imgChange(img){
img.src = "./Images/img2.png";
}
Seems to work perfectly in the example below. I would suggest checking that the references to the image sources you are using are valid, as that's the only thing I changed.
function imgChange() {
var img = document.getElementById("img");
img.src = "https://www.tompetty.com/sites/g/files/g2000007521/f/styles/photo-carousel/public/Sample-image10-highres.jpg?itok=TDZEPjP8";
}
<input type="image" src="https://www.tompetty.com/sites/g/files/g2000007521/f/styles/photo-carousel/public/sample001.jpg?itok=0Riiujkr" id="img" onclick="imgChange()">
should work as is,
but you could try passing the element into the function.
function imgChange(img){
img.src = "https://w.wallhaven.cc/full/pk/wallhaven-pkgkkp.png"
}
<img src="https://w.wallhaven.cc/full/rd/wallhaven-rdwjj7.jpg" onclick="imgChange(this)">

adding image file to change background image in javascript

So hi hello there first of all...
I ran into a little problem and am having a tough time trying to figure it out.
So basically what i am trying to do is be able for the user to click on a button that will allow them to select an image and after that it will grab the url of that image locally and change the background image of a div.
Now i am using the window variable but thinking about trying this out without it and just having the event listener do its thing. But havent tested that out kinda of feel like that wont work.. just a thought. but anyways, this works for when i only have one event listener target the button but if i do 2 then it gives me a security warning telling me that it may not load data from the blob... any idea of how to proceed with the vision?
Below is the html code:
<h3 class="m-heading">Project</h3>
<div class="projectIMG">
<input type="file" id="projectImgBtn">
</div>
Below is the javscript
window.addEventListener('load', function(){
fileButton.addEventListener('change', function(){
if(this.files && this.files[0]){
const background = document.querySelector('.insertImage');
console.log(background)
// console.log(background.style.backgroundImage)
background.style.backgroundImage = `url('${URL.createObjectURL(this.files[0])}')`
background.onload = imageLoaded;
}
})
projectImg.addEventListener('change', function(){
if(this.files && this.files[0]){
const background = document.querySelector('.projectIMG')
console.log(background)
background.style.backgroundImage = `url('${URL.createObjectURL(this.files[0])})`
background.onload = imageLoaded
}
})
})
This is the full error
yout need to get the base64 for put it in the background.
Try this:
const reader = new FileReader();
reader.onload = e => variable = e.target.result;
reader.readAsDataURL(this.files[0]);

onload not working in <img> element

I don't understand why this function doesn't fire. I want to declare an image in HTML with a single onload function, which will automatically take care of the image's source and mouseover/out functions.
The HTML looks like this:
<img id="menuBtnNovo" onload="imgButton(this)"/>
and the JS function imgButton looks like this:
function imgButton(e){
window.alert("asdasdad");
e.src="images/def/" + e.Id + ".png";
e.onmouseover= function(){ *change image here*}
e.onmouseout= function(){ *change image back here*}
}
Now, not even the alert pops up, and I don't know why. I tried putting script in <head> and setting src to none src="" in the <img>. I'm using Firefox, but it doesn't work in Edge either.
Question is: how do I fire onload function on an image element?
Also, if you have any idea of your own way of implementing this behaviour of automatically loading certain images (that would actually be buttons/links), feel free to share it. I'm new to JS but not to programming.
As you might see, all images are in "images/def/..." and all images for when the mouse is over the img are in "images/mo/...".
I always try and let browser do image replacements, but if you have to use script, than you can do something like this on DOM ready, or window load event:
$('img[data-regular]').each(function(i) {
var thisImage = $(this);
var regular = thisImage.data('regular');
var hover = thisImage.data('hover');
thisImage.attr('src', regular);
/* Preload image for hover */
$('<img/>')[0].src = hover;
/* Set events */
thisImage.on('mouseenter', function(e) {
thisImage.attr('src', hover);
}).on('mouseleave', function(e) {
thisImage.attr('src', regular);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img data-regular="https://placehold.it/350x150" data-hover="https://placehold.it/450x200" />
Also on JSFiddle.

Gif loader while loading heavy png image

I load png image generated by server-side PHP script (chart) to the HTML IMG-element <img id="chart"> using following JS code:
$('#chart').attr('src', 'chart.php');
The PNG-image generation and downloading takes about 1 second, so I want to show gif loader while image is loading. How to implement this feature with JS?
For balance this is very simple to do in plain JS:
var preload = function(element, src) {
var img = new Image();
// Apply onload before applying src attribute to avoid IE prematurely firing
img.onload = function() {
// Replace #chart with image
element.parentNode.replaceChild(img, element);
};
img.src = src;
}
preload(document.getElementById('chart'), 'chart.php?_...');
$('#chart').attr('src', 'chart.php').load(function(){
//something
});
In case the browser caches it, you may way to add something to the query string to break that. Either way, you need to listen for the image's load event, which should be bound before setting its src (in case it's cached):
var target_url = 'chart.php?_=' + (new Date()).getTime();
// Show "loading"
$('#chart').on("load", function () {
// Hide "loading"
}).attr('src', target_url);
Reference:
http://api.jquery.com/load-event/
Note the caveats near the bottom of that reference, referring to the event when working with images:
It doesn't work consistently nor reliably cross-browser
It doesn't fire correctly in WebKit if the image src is set to the same src as before
It doesn't correctly bubble up the DOM tree
Can cease to fire for images that already live in the browser's cache

JavaScript event for when image 'src' attribute is changed?

I have a function resizePreview() that will resize an image in a jQuery dialog box if the image is too big. This image can be changed by the user. My code goes something like this:
$('#imagePreview').attr('src', newImageSrc);
resizePreview();
resizePreview() uses $('#imagePreview').width() and .height() to get the dimensions and resizes accordingly. The problem is that the new image isn't loaded by the time resizePreview() is called so the image is resized according to it's original dimensions, not according to the dimensions of the newly loaded image.
If I put an alert() call in between the two lines of code it works (since the alert gives the browser enough time to load the new image). Apparently I should use an event? Is there an existing event, or is there a way I can make one, for when the image src has changed (sort of like an onChange event, but for that attribute) or for when the new image has completed loading?
The load event works for Images:
$('img.userIcon').on('load', function () {
$(this).toggleClass( 'bigImg', $(this).height() > 100 );
});
Image objects allow attachment of onload event listeners:
var img = new Image;
img.onload = function () {
alert("Loaded");
};
img.src = "dummy-picture.png";

Categories

Resources