Why is only the first mouse-over and mouse-out working? - javascript

I have loaded a set of images and applied .mouseout() and .mouseover() on them. The problem is that after the first .mouseover() event the image gets larger and after .mouseout() is fired the image is returned back to its previous size. After the first time, no .mouseover() event gets fired in Firefox, but in Chrome it works. The problem is that the Chrome z-index property does not put the mouseover image on top of other images. What is the reason for these problems and how can I solve them?
var images = ['http://www.rd.com/wp-content/uploads/sites/2/2016/04/01-cat-wants-to-tell-you-laptop.jpg', 'http://r.ddmcdn.com/s_f/o_1/cx_462/cy_245/cw_1349/ch_1349/w_720/APL/uploads/2015/06/caturday-shutterstock_149320799.jpg', 'http://r.ddmcdn.com/s_f/o_1/cx_462/cy_245/cw_1349/ch_1349/w_720/APL/uploads/2015/06/caturday-shutterstock_149320799.jpg', 'http://pershanpet.ir/wp-content/uploads/2016/05/144-jpravafcbn.jpg', 'http://www.animal-whisper.com/images/pic28.jpg'];
function loadImage(url) {
var promise = new Promise((resolve, reject) => {
var image = new Image();
image.onload = function() {
resolve(image);
};
image.onerror = function() {
var msg = "could not load image at url " + url;
reject(new Error(msg));
};
image.src = url;
image.style.width = '200px';
image.style.height = '200px';
});
return promise;
}
Promise.all(
images.map(function(elem) {
return loadImage(elem);
})
).then((img) => {
img.forEach(each => {
each.addEventListener('mouseover', function(event) {
this.style.zIndex = '2000';
this.style.transform = 'scale(1.5,1.5)';
});
each.addEventListener('mouseout', function(event) {
this.style.transform = 'scale(1,1)';
this.style.zIndex = '-1';
});
addImg(each);
});
});
function addImg(img) {
document.body.appendChild(img);
}

Maybe your images get under some other elements with z-index that is greater than -1. On mouseout try this.style.zIndex = '0'.

It appears that you're setting the image's z-index to -1. Any reason for that?
Try setting this.style.zIndex = '1'; on mouseout.

Related

Defer image and replacement loaded

I have a JS function that once the page is loaded swaps the assets from a transparent gif to full images via the data-src below.
<img src="1x1.gif" data-src="full-photo.png" class="asset" /> // My image
window.addEventListener('load', function() {
defer_images();
function defer_images() {
var loadedImages = 0;
var imgDefer = document.getElementsByClassName('asset');
for (var i = 0; i < imgDefer.length; i++) {
if (imgDefer[i].getAttribute('data-src')) {
imgDefer[i].setAttribute('src',imgDefer[i].getAttribute('data-src'));
var iWidth = imgDefer[i].naturalWidth; // Check image exists
if (iWidth) {
loadedImages++;
} else {
console.log("Image missing: "+imgDefer[i].getAttribute('data-src'));
}
}
// all images exist and have been replaced
if (imgDefer.length === loadedImages) {
doThings();
}
}
}
});
This seems to work fine on a cached page. But if I reload the page and switch tabs – the code doesn't complete as loadedImages++ is never fired.
I can't use setInterval or setTimeout to re-check as this code is used in DoubleClick.
Any help would be really appreciated.
You can detect that images are loaded by using the onload event and failed to load using onerror.
for (var i = 0; i < imgDefer.length; i++) {
var img = imgDefer[i];
if (img.getAttribute('data-src')) {
img.addEventListener("load", function() {
loadedImages++;
});
img.addEventListener("error", function() {
console.log("Image missing: "+ this.getAttribute("data-src"))
});
img.src = img.getAttribute('data-src');
}
}
The reason it fails for non-cached is because it takes time to load the image, and your for loop is fast. Use the events to trigger when the image is loaded.
You can read more here.
Note: Detecting that all images are loaded may require using promises:
function loadImage(src) {
return new Promise((resolve, reject) => {
const img = new Image();
img.addEventListener("load", () => resolve(img));
img.addEventListener("error", err => reject(err));
img.src = src;
// append to the dom or replace here
});
};
Then you can use then() and catch()

get uploaded image height and width on callback -javascript

I need to load multiple image asynchronously from file field and them check if the dimensions are valid or not. I am pretty close, I just need to get the height of previously loaded image on call back. This is my effort so far:
let files = this.fileUpload.files; //get all uploaded files
for (var i = 0, f; f = files[i]; i++) { //iterate over uploaded file
console.log(f);
let img = new Image();
img.name=f.name;
img.size=f.size;
img.onload = () =>{alert(img.height)} //it is giving height here
if (img.complete) { //callback
alert(img.name + 'loaded');
load_count++;
library_store.uploaded_image.push(
{
height:img.height,
width:img.width, // not coming, just wondering how to get
//the image height from load
name:img.name,
size:img.size
}
);
}
if(load_count === uploaded_file_count){ // if all files are loaded
//do all validation here , I need height and width here
}
What is the best way to do this?
Wouldn't you want to move library_store logic to img.onload? Like below:
let files = this.fileUpload.files; //get all uploaded files
for (var i = 0, f; f = files[i]; i++) { //iterate over uploaded file
console.log(f);
let img = new Image();
img.name=f.name;
img.size=f.size;
img.onload = function() {
// hoping that ```this``` here refers to ```img```
alert(this.name + 'loaded');
load_count++;
library_store.uploaded_image.push({
height:this.height,
width:this.width,
name:this.name,
size:this.size
});
if(load_count === uploaded_file_count){ // if all files are loaded
//do all validation here , I need height and width here
}
}
// img.onload = () =>{alert(img.height)} //it is giving height here
/*
if (img.complete) { //callback
alert(img.name + 'loaded');
load_count++;
library_store.uploaded_image.push({
height:img.height,
width:img.width,
name:img.name,
size:img.size
});
if(load_count === uploaded_file_count){ // if all files are loaded
//do all validation here , I need height and width here
}
}
*/
}
First let's see why you will always fall in this if(img.complete) block even though your images have not been loaded yet:
The complete property of the HTMLImageElement only tells if its resource is being loaded at the time you get the property.
It will report true if the loading succeed, failed, and if the src has not been set.
var img = new Image();
console.log('no-src', img.complete);
img.onerror = function() {
console.log('in-error', img.complete);
img.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQImWNgYGBgAAAABQABh6FO1AAAAABJRU5ErkJggg=="
};
img.onload = function() {
console.log('in-load', img.complete);
}
img.src = "/some/fake-path.png";
console.log('while loading', img.complete);
And, at the time you get it, you didn't set this src attribute yet, so it will report true even though your image has not yet loaded its resource.
So what you want is an image preloader:
function preloadImages(srcArray, mustAllSucceed) {
return Promise.all(srcArray.map(loadImage));
function loadImage(src) {
return new Promise((resolve, reject) => {
var img = new Image();
img.onload = success;
img.onerror = mustAllSucceed ? success : reject;
img.src = src;
function success() {
resolve(img)
};
});
}
}
preloadImages(['https://upload.wikimedia.org/wikipedia/commons/5/55/John_William_Waterhouse_A_Mermaid.jpg', 'https://upload.wikimedia.org/wikipedia/commons/9/9b/Gran_Mezquita_de_Isfah%C3%A1n%2C_Isfah%C3%A1n%2C_Ir%C3%A1n%2C_2016-09-20%2C_DD_34-36_HDR.jpg'])
.then(images => {
images.forEach(img => console.log(img.src, img.width, img.height));
}, true);

Src for the images does not set properly

I have some divs that has a class named class='tweetCon'
each containing 1 image and I want to check if the image source exist or not so if it is available I dont do anything but if not I will change the image source with an appropriate image my code is as follow:
$('.tweetimgcon').children('img').each(function () {
imageExists($(this).attr("src"), function (exists) {
if (exists == true) {
} else {
$(this).attr("src", "https://pbs.twimg.com/profile_images/2284174758/v65oai7fxn47qv9nectx.png");
}
}, function () {
});
});
and also imageExists() is as follow:
function imageExists(url, callback,callback2) {
var img = new Image();
img.onload = function() { callback(true);callback2(); };
img.onerror = function() { callback(false);callback2(); };
img.src = url;
}
now the problem is that the src for the images that are not available does not set properly though when I check the src of those images by console.log it shows that they are properly set but it is not shown and when I use inspect element of chrome I can see that src is not set . Can anyone help me?
The point is $(this) doesn't point to your object, because you call $(this) inside your imgExists callback function but NOT the jQuery callback function each, so the this object doesn't point to your original img tag!
The solution should be save the object reference first, try the below:
$('.tweetimgcon').children('img').each(function () {
var _this = $(this);
imageExists($(this).attr("src"), function (exists) {
if (exists == true) {
} else {
_this.attr("src", "https://pbs.twimg.com/profile_images/2284174758/v65oai7fxn47qv9nectx.png");
}
}, function () {
});
});
Just for a little tip for a better callback function use call.
function imageExists(url, cb, ecb) {
var img = new Image();
img.onload = function() { cb.call(img,true,url); };
img.onerror = function() { ecb.call(img,false,url); };
img.src = url;
}
I added img as the first argument and that will then be your this keyword instead of window.
Testing Bin

How to Hide an Image, if not clicked, in N seconds?

I have a button that when is clicked, an image is created using javascript and get prepended to a div (adds it inside a div).
var image = new Image();
var imageHtml = image.toHtml();
$('div.board').prepend(imageHtml);
function Image()
{
this.toHtml = function ()
{
return '<img src=\"myImage.png\" width=\"40px\" height=\"40px\" />';
}
}
This image can be clicked in 2 seconds then user will have 1 more score and if not clicked in that time, then the image should disappear.
How to do that in javascript?
Thanks,
function start_game(image){
var timeout = null;
image.onclick = function(){
clearTimeout(timeout);
//addScore();
};
timeout = setTimeout(function(){
image.onclick = null;
image.style.display = "none";
// remove the image from dom if needed;
}, 2000);
}
Demo: http://jsfiddle.net/UpNCb/
see this, just difference is you going to hide instead of link display
or
give id 'img_id' to your image
function hideimage() {
document.getElementById('img_id').style.display = 'none';
}
setTimeout(hideimage, 10000);
Use the function setTimeout() and the CSS property display or visibility.

Checking for multiple images loaded

I'm using the canvas feature of html5. I've got some images to draw on the canvas and I need to check that they have all loaded before I can use them.
I have declared them inside an array, I need a way of checking if they have all loaded at the same time but I am not sure how to do this.
Here is my code:
var color = new Array();
color[0] = new Image();
color[0].src = "green.png";
color[1] = new Image();
color[1].src = "blue.png";
Currently to check if the images have loaded, I would have to do it one by one like so:
color[0].onload = function(){
//code here
}
color[1].onload = function(){
//code here
}
If I had a lot more images, Which I will later in in development, This would be a really inefficient way of checking them all.
How would I check them all at the same time?
If you want to call a function when all the images are loaded, You can try following, it worked for me
var imageCount = images.length;
var imagesLoaded = 0;
for(var i=0; i<imageCount; i++){
images[i].onload = function(){
imagesLoaded++;
if(imagesLoaded == imageCount){
allLoaded();
}
}
}
function allLoaded(){
drawImages();
}
Can't you simply use a loop and assign the same function to all onloads?
var myImages = ["green.png", "blue.png"];
(function() {
var imageCount = myImages.length;
var loadedCount = 0, errorCount = 0;
var checkAllLoaded = function() {
if (loadedCount + errorCount == imageCount ) {
// do what you need to do.
}
};
var onload = function() {
loadedCount++;
checkAllLoaded();
}, onerror = function() {
errorCount++;
checkAllLoaded();
};
for (var i = 0; i < imageCount; i++) {
var img = new Image();
img.onload = onload;
img.onerror = onerror;
img.src = myImages[i];
}
})();
Use the window.onload which fires when all images/frames and external resources are loaded:
window.onload = function(){
// your code here........
};
So, you can safely put your image-related code in window.onload because by the time all images have already loaded.
More information here.
A hackish way to do it is add the JS command in another file and place it in the footer. This way it loads last.
However, using jQuery(document).ready also works better than the native window.onload.
You are using Chrome aren't you?
The solution with Promise would be:
const images = [new Image(), new Image()]
for (const image of images) {
image.src = 'https://picsum.photos/200'
}
function imageIsLoaded(image) {
return new Promise(resolve => {
image.onload = () => resolve()
image.onerror = () => resolve()
})
}
Promise.all(images.map(imageIsLoaded)).then(() => {
alert('All images are loaded')
})
Just onload method in for loop does not solve this task, since onload method is executing asynchronously in the loop. So that larger images in the middle of a loop may be skipped in case if you have some sort of callback just for the last image in the loop.
You can use Async Await to chain the loop to track image loading synchronously.
function loadEachImage(value) {
return new Promise((resolve) => {
var thumb_img = new Image();
thumb_img.src = value;
thumb_img.onload = function () {
console.log(value);
resolve(value); // Can be image width or height values here
}
});
}
function loadImages() {
let i;
let promises = [];
$('.article-thumb img').each(function(i) {
promises.push(loadEachImage( $(this).attr('src') ));
});
Promise.all(promises)
.then((results) => {
console.log("images loaded:", results); // As a `results` you can get values of all images and process it
})
.catch((e) => {
// Handle errors here
});
}
loadImages();
But the disadvantage of this method that it increases loading time since all images are loading synchronously.
Also you can use simple for loop and run callback after each iteration to update/process latest loaded image value. So that you do not have to wait when smaller images are loaded only after the largest.
var article_thumb_h = [];
var article_thumb_min_h = 0;
$('.article-thumb img').each(function(i) {
var thumb_img = new Image();
thumb_img.src = $(this).attr('src');
thumb_img.onload = function () {
article_thumb_h.push( this.height ); // Push height of image whatever is loaded
article_thumb_min_h = Math.min.apply(null, article_thumb_h); // Get min height from array
$('.article-thumb img').height( article_thumb_min_h ); // Update height for all images asynchronously
}
});
Or just use this approach to make a callback after all images are loaded.
It all depends on what you want to do. Hope it will help to somebody.
try this code:
<div class="image-wrap" data-id="2">
<img src="https://www.hd-wallpapersdownload.com/script/bulk-upload/desktop-free-peacock-feather-images-dowload.jpg" class="img-load" data-id="1">
<i class="fa fa-spinner fa-spin loader-2" style="font-size:24px"></i>
</div>
<div class="image-wrap" data-id="3">
<img src="http://diagramcenter.org/wp-content/uploads/2016/03/image.png" class="img-load" data-id="1">
<i class="fa fa-spinner fa-spin loader-3" style="font-size:24px"></i>
</div>
<script type="text/javascript">
jQuery(document).ready(function(){
var allImages = jQuery(".img-load").length;
jQuery(".img-load").each(function(){
var image = jQuery(this);
jQuery('<img />').attr('src', image.attr('src')).one("load",function(){
var dataid = image.parent().attr('data-id');
console.log(dataid);
console.log('load');
});
});
});
</script>

Categories

Resources