JavaScript Image Loading - javascript

When I am click on a button then a javascript function is invoked and it loads the image in the page. But the image is not loading properly. The image size is 72kb and the image coming from the DB and it's already loaded in the server start.
If I put any alert message then the image loads properly. What's the reason behind the issue?
var catImg = document.getElementById(\"CategorySampleImage\");
var oldImgSrc = catImg.src;
var newImgSrc = oldImgSrc.substr(0,oldImgSrc.indexOf(\"images\"))+\"images/\"+\""+imageName+"\";
catImg.src=newImgSrc;
for (var intCounter = 1; intCounter <= 500; intCounter++){
for (var counter = 1; counter <= 500; counter++)
{
if(counter==500)
break;
}
}
document.getElementById(\"light\").style.display=\"block\";
document.getElementById(\"fade\").style.display=\"block\";";
code works fine for all browsers except IE6. In IE6 I can see a white area in place of the Image and I need to right click on theat white area and select “Show Image”. But a smaller image in the same div displays correctly. Don't know how could I solve this issue on IE6.

You can use onload event on the image object when loading it to make sure that it is already loaded.
Ex.
catImg.onload = function(){ /* Image is loaded. Do something here*/ }

Related

How can I load an image before it's needed?

I'm developing a website with an image gallery. There is a grid of images with dozens of thumbnails. When a user clicks on an image a div slides down from the top. That div's CSS gets edited with JavaScript to change the background-image.
My problem is that the div slides down, but the background image "flickers" in randomly. What I want is the div to slide down with the image already loaded. I'm not sure how to solve this problem because I think it would be unreasonable to pre-load every thumbnail's larger version when the user most likely won't click on them all.
You can convert the image to base64 and enable it in src of the img tag, after that send in the dormulário.
this use example: https://hdtuto.com/article/how-to-convert-image-into-base64-string-jquery
One way to preload images is to create an image object using javascript
Here's an example:
HTML:
<img src="photo1.jpg" id="photo" />
Javascript:
var photo = document.getElementById("photo");
var loadImage = new Image();
loadImage.src = "YourSrc/image.jpg";
Last step, use this code in your event handler when you want to change to the preloaded image:
photo.src = loadImage.src;
If you are looking to preload multiple images use an array and a loop.
imageSrcs = ["imgsrc1.jpg", "imgsrc2jpg", "imgsrc3jpg"];
preloadedImages = [];
for(var i = 0; i < imgSrcs.length; i++)
{
preloadedImages[i] = new Image();
preloadedImages[i].src = preloadedImages[i];
}

introducig changes in style by jQuery

i've created simple code that should set/change image background depending on window width
var backgroundBig = "url(../img/logo1.svg)";
var backgroundSmall = "url(../img/logo2.svg)";
function logoBG(){
var windowWidth = $(window).width();
if (windowWidth < 700){
$("#wrapper1").css({"background-image": backgroundSmall});
} else {
$("#wrapper1").css({"background-image": backgroundBig});
};
};
logoBG();
$(window).resize(logoBG);
as simple as that...
optional background image proprieties are set in css file
#wrapper1{
background-repeat: no-repeat;
background-size: cover;}
everything works fine in website code - when i'm tracking changes by firebug, code changes as it should. however, images don't load, nothing changes regarding website display. what is wrong with that?
thanks in advance
PM
Try this https://jsfiddle.net/2Lzo9vfc/23/
JS
var backgroundBig = "url(http://placehold.it/1980x960)";
var backgroundSmall = "url(http://placehold.it/1980x960/000000)";
function logoBG(){
var windowWidth = $(window).width();
if (windowWidth <= 700){
$("#wrapper1").css("background-image", backgroundSmall);
} else {
$("#wrapper1").css("background-image", backgroundBig);
};
};
logoBG();
$(window).resize(logoBG);
$(document).ready(logoBG);
HTML
<div id="wrapper1">Lorem</div>
Because the images must be loaded FIRST, why it's working with firebug ? it's surely because firebug reload the DOM so he can parse it, and when he do so, the images are already loaded.
I can recommend you jquery.waitForImages because it can even wait for images background, so your JavaScript code is not executed before your images are loaded, and you dont need to Reload the DOM too.
Thank you for all advices. The problem with my code was... the paths to my image files.
url(../img/logo1.svg)
works in css file, that's why I assumed that it's must be correct, but
url(img/logobg.svg)
should be inserted by the jQuery script. What a lame mistake :)

jQuery script doesn't work on uploaded image

I have this jQuery code which centralizes an image within a DIV horizontally and vertically:
var $itemImage = $('.a-img');
$itemImage.each(function() {
var $img = $(this);
var h = $img.height();
var w = $img.width();
$img.css('margin-top', +h / -2 + "px").css('margin-left',+ w/ -2 + "px");
});
It works when the page is first loaded. However, there's a link on the page that will show a pop-up box where you can update the photo. Once you click "Upload" on the pop-up box, the image on the main page will change without refreshing the entire page. The jQuery code that initially applied to the image no longer works (the image is no longer centralized).
How do I solve this problem?
Put this into a function, and call this function when you load the image. Oh, and this is JavaScript. Remove the $ on the variables: itemImage instead of $itemImage, img instead of $img.

Javascript - Image change an resize to full background

As a quick explanation, I created an image that resizes to fill the background using this function which works great:
function resize_bg(element_id){
$("#"+element_id).css("left","0");
var doc_width = $(window).width();
var doc_height = $(window).height();
var image_width = $("#"+element_id).width();
var image_height = $("#"+element_id).height();
var image_ratio = image_width/image_height;
var new_width = doc_width;
var new_height = Math.round(new_width/image_ratio);
if(new_height<doc_height){
new_height = doc_height;
new_width = Math.round(new_height*image_ratio);
var width_offset = Math.round((new_width-doc_width)/2);
$("#"+element_id).css("left","-"+width_offset+"px");
}
$("#"+element_id).width(new_width);
$("#"+element_id).height(new_height);
return true;
}
So no problem for the full background image. The problem appears, when I change the image source using Javascript. In other words, I have 1 image set as background but on hover of certain elements on the page, the image changes but it doesn't change the resize right. So the first image on load is resized and positioned correctly, but when I switch the image using .attr('src',newimg) the image is not resized correctly even though I call the function again.
Here is the code I use to change the image and resize it:
$('#menu_work li a').hover(function(){
$('#content').hide();
var img_src = $(this).next('img').attr('src');
$('#full_screen_img').attr('src', img_src );
resize_bg();
$('#full_screen_img').show();
},function(){
$('#full_screen_img').hide();
$('#content').show();
});
Thanks for any help.
It appears that you have left out the element_id argument when calling resize_bg() in the hover event handler. As a result, resize_bg() can't find the element you want to resize.
#maxedison is right, you forgot to pass the element id.
Another problem is that when you change the src, the new image might not be loaded yet, so you won't get the right dimensions in resize_bg until it is.
In that case you'll need to resize the image once it's loaded:
$('#full_screen_img').attr('src', img_src ).load(function() {
resize_bg('<ELEMENT_ID>');
});
resize_bg('<ELEMENT_ID>');
On another note, I'd recommend you change resize_bg to get a jQuery object instead of an id, or even write a plugin ($.fn.resize_bg) if it's a functionality you want to use often.

Sizing/stretching images to dimensions known only after page load

On my website, users can upload large images. I display these images like this:
<img id="userImage" src="userImage.ashx?width=740&id=4fc265d4-a83c-4069-8d6d-0fc78ae2840d">
userImage.ashx is a handler that returns image files based on id, so in this example the image for user 4fc265d4-a83c-4069-8d6d-0fc78ae2840d is returned. You can also set other attributes - in this example only width is given. The image is resized so that it is 740px wide.
I set the src of the image in javascript, once the rest of the page has loaded. By doing this I know how wide the image has to be to fill all the available space:
var width = document.getElementById("userImageHolder").getComputedSize().width;
document.getElementById("userImage").src = "flash/userImage.ashx?type=micrositePhoto&id=" + userId + "&width=" + width;
This all works, but the image doesn't load until everything else on the page has loaded. I have a complex solution to a simple problem.
Is there a better way to do this? What is the best way to shrink/stretch images to fill an area that is only known once the page loads?
Figure out what the upper limit is for width and height and generate the image to that size, then use max-width/max-height to allow the browser to auto scale it based on the size of the browser window.
Try to preload your images in a onDOMReady handler, and then insert in an onLoad one. While this can't guarantee the images to be loaded before everything else, they can at least start loading earlier.
Someting like this (using jQuery):
$(document).ready(function(){
var imageArray = [],
imageSrc = [];
//Fill image src array from somewhere
var len = imageSrc.length;
for(var i = 0; i < len; i++){
var img = new Image();
img.src = imageSrc[i];
img.onload = function(){
//Do something with your loaded image
imageArray.push(this);
}
}
});

Categories

Resources