change background image, when big size umage loads - javascript

i have a div element, with very big size background image. so, is it possible, to set a little size image as backgrount, untill the big size image loads.
thanks

I guess you could put another div element underneath it (using the z-index property) and give that the faster loading background image.
Whether that is practical to do, depends on your Layout, you'd have to give more information about that.
There's also the ages-old lowsrc HTML 4 property that still seems to be pretty well supported (I have not tried it myself since Netscape 4), but that won't work for background images.

CSS:
.that-div {
background-image:url(/path/to/small-image.png);
}
jQuery:
$(function () {
var bigImg = new Image(),
bigImgSrc = '/path/to/big-image.png';
bigImg.src = bigImgSrc;
$(bigImg).load(function(){
$('.that-div').css('background-image':'url('+bigImgSrc+')');
});
});

Related

Issue with high resolution images in chrome(windows) loading from javascript

I am having a problem with a site. My problem is I am loading several images progressively - starting with a small resolution image for fast loading I am then ajaxing a bigger image in (normally the original size that a user uploads).
The code below works perfectly. HOWEVER when done on chrome on windows. if the bigger image is a really high res (lets say 4400 x 4000). The screen would go white and the image would disappear. The white bursts out of the container (which has overflow:hidden) on it and covers the screen. Only the elements with a higher z-index over the image displays.
If I inspect the element that is white. It shows that it is the element, and the image is loaded - the URL is fine and if I click the image to open in another tab it loads fine.
Does anyone have any idea why this is happening?
if(href){
var img = document.createElement('img');
img.className = 'openLBFullView hidden';
img.onload = function(){
loadBiggerImg(this);
};
$(img).data('url',$currentImg.data('url'));
img.src = href;
img.id = 'my-image';
}
var loadBiggerImg = function(img){
var originalImg = $('#my-image');
//append the img to the document
originalImg.before(img);
// append original styles and classes to new image
$(img).attr('style',originalImg.attr('style'));
$(img).attr('class',originalImg.attr('class'));
// fix for windows IE adding attributes
$(img).removeAttr('width').removeAttr('height');
//fade in new image over the top and remove old one
$(img).fadeIn(200,function(){
originalImg.remove();
});
}
One of the possible solutions - large images dont render in chrome
This not neccesarily will fix your issue though - I'd try using lowres jpegs scaled to highres and preload big one - once loaded fade lowres one and show the big one (in a way fake the progressive JPEG) - Hope that helps man.

Improve image load time

I have a few img tags whose src is changed onmouseover. This takes an inordinate amount of time to load. How can I improve the load time? The images are basically just different icons.
You can do a few things.
1) CSS Sprites is probably the preferred method.
2) You can load the images in a div and set that div to display none, making it so the images are already loaded so on mouseover they'll be there instantly.
Also here's a link on how to PreLoad images with CSS
There are a few ways to do it, the ideal solution in your case would be to use CSS sprites considering they're icons. However, depending on the situation sometimes sprites aren't ideal.
Here's one solution using JavaScript to preload images:
var images = new Array();
function preload() {
for (i = 0; i < preload.arguments.length; i++) {
images[i] = new Image();
images[i].src = preload.arguments[i];
}
}
preload(
'http://image-1.jpg',
'http://image-2.jpg',
'http://image-3.jpg'
);
What you're trying to do is achieve a rollover. It is strange that you'd experience a very long delay in this process. Usually, if the images aren't stored in some remote location, they're pretty fast.
Look at this article for some guidance
Other things you could try:
- sprites in css
- you could use two overlapping divs and hide one and unhide the other and vice versa

Display image on top of page with big 3 + jquery, in FireFox?

Would like to bring a single image to the front or on top of the page, when selected.
After searching, it seems there are many plug-ins that support this - but also have a lot of other functionality and overhead I don't need (gallery, support for video, thumbnails, etc.)
Is it possible to just bring a single image on top with basic JavaScript, CSS, HTML and jQuery, specifically in FireFox?
Thank You.
(Please note*: This is an in house product, hence these requirements and constraints.)
Is it possible to just bring a single image ontop with basic JavaScript, CSS, HTML and jQuery, specifically in FireFox?
Yes, it's possible, but the plugins are most of the time an easier implementation. What you are trying to accomplish is something similar to the light box effect, but I'll try to give a simple solution based on 4 steps you need to accomplish what you are trying to do:
Create an overlay div. This one div will blur or darken your entire page. In the below example it will darken your screen (because it's simpler).
Create an div that will be appended to the overlay div and will contain the image you want to show. In the demo below, this div will be lighter than the overlay one and will actually have half the width and half the height of your screen.
Append a bigger image to your image-div.
Add a subtitle to your image based on it's alt text.
$(document).ready(function()
{
var docWidth = $(document).width();
var docHeight = $(document).height();
//First Step" Creating the overlay-div and adding opacity to it
var overlayDiv = "<div id="overlay-div"></div>"
$("body").append(overlayDiv);
$("#overlay-div").css("position","absolute", "top","0","left","0","background-color","#000","opacity","0.5", "width", docWidth + "px", "height",docHeight + "px");
//Second step: Creating the image-div and centering it on the screen
$("#overlay-div").append("<div id=\"image-div\"></div>");
$("#image-div").css("position","absolute", "top",docHeight/4 + "px","left",docWidth/4 + "px","background-color","#FFF", "width", docWidth/2, "height",docHeight);
//Third step: Creating an image to display inside the image-div and centering it
$("#image-div").append("<img src=\"path/to/your/image\"id=\"zoomed-img\" alt=\"This is a zoomed image\"/>");
var imgWidth = $("#image-div").width();
var imgHeight = $("#image-height").height();
$("#image-div").css("position","absolute", "top","10px","left","10px");
//Fourth step: Creating a subtitle from the alt text
var subtitle = "<p id=\"text-subtitle\">" + $("#image-div").attr("alt") + "</p>";
$("#image-div").append(subtitle);
$("#text-subtitle").css("position","absolute", "top",imgHeight + 20 + "px","left","10px");
});
This function is triggered when your document is ready, and get an arbitrary image. But it's possible to display a different image (with a different subtitle) triggered by a click with a little tweak of the code above.
I had the intention to show you a simple demo that it's feasible to with with a few lines of jQuery/javascript code to create what you want. Of course it's not as pretty as 90% of the effects of the plugins there are around but it may be a start.
I hope it helped. Cheers
Here is a very basic example I whipped up. Hopefully good to learn from:
http://jsfiddle.net/v9LTP/2/
$('img').click(function(){ //bind a click event handler to images
var img = $(this).clone().addClass('modal').appendTo($('#blackout')); //clone the clicked image element and add to the blackout div which gives the dark background.
$('#blackout > #close').click(function(){ //attach click handler to close button
$('#blackout').fadeOut(function(){ //fade the blackout div
img.remove(); //remove the image element we cloned, so we can do it again.
});
});
$('#blackout').fadeIn(); //show the blackout div
});
​
For a stupid simple lightbox I've been leveraging http://buckwilson.me/lightboxme/ lately.
Try Modals of Bootstrap.
JavaScript - Twitter Bootstrap
GitHub source code
GitHub bootstrap-modal.js

Javascript load background-image asynchrously

Is it possible to load a background-image asynchronously?
I've seen many jQuery plugins to load normal image in an asynchronous way, but I can't find if it's possible to preload / asynchronously load a background-image.
EDIT
I clarify my problem. I've been working on this test site http://mentalfaps.com/
The background image is loaded randomly from a set of images refreshed each hour by a chron job (which takes random images on a flickr catalog).
The host is free and slow at the moment, so the background image takes some time to load.
The positioning of the first overlay (the one with the PNG transparent mentalfaps logo) and width are regulated by a function created in the jQuery(document).ready construct.
If you try to refresh the page many times, the width of the right overlay div is 0 (and so you see a "hole" in the layout)
Here is the method to set my positions:
function setPositions(){
var oH = $('#overlay-header');
var overlayHeaderOffset = oH.offset();
var overlayRightWidth = $(window).width() - (overlayHeaderOffset.left + oH.width());
if (overlayRightWidth >= 0) {
$('#overlay-right').width(overlayRightWidth);
} else {
$('#overlay-right').width(0);
}
var lW = $('#loader-wrapper');
lW.offset({
left: (overlayHeaderOffset.left + oH.width() - lW.width())
});
}
The problem is that the $(window).width() is lower then the effective window width! so the check fails and the script goes for $('#overlay-right').width(0);
any ideas?
Not sure whether I really understand your question, but background images (and all other images) are already loaded asynchronously - the browser will start separate requests for them as soon as it encounters the URL while parsing the HTML.
See this excellent answer for background on loading order: Load and execution sequence of a web page?
If you meant something else, please clarify.
The trick to loading something in the background is to load it once, so the next time when it is loaded it already is in the cache.
Put the following at the end of your html:
<script>
var img = new Image();
img.onload = function () {
document.getElementsByTagName('body')[0].style.backgroundImage = 'background.png';
};
img.src = 'background.png';
</script>
You could use a prefetch link in the head.
<link rel="prefetch" href="/images/background.jpg">
You should be able to add these links to the head via JavaScript.
I like to use CSS to fill the background with a color for page load.
After DOM ready event, I use jQuery to modify the CSS and add a background image. That way, the image isn't loaded until after page loads. Not sure about async, but this method gives the user a decent experience.
Example: http://it.highpoint.edu/
The right side navigation links have a background image. The page initializes with a background color. It is replaced with a background image after page load, via jQuery.
changes in this file jquery.ImageOverlay.js
set your height and width and enjoy this...
imageContainer.css({
width : "299px",
height : "138px",
borderColor : hrefOpts.border_color
});
As it is already mentioned, the background image is loaded asynchronously. If you need to load the background image from JQuery code you may also set the addClass() method to set a CSS class or attr("style=\"background-image:url('myimage.png')\"")
Ive found the answer myself, it was a problem due to the .offset() method that gived sometimes the wrong values.
I had the write values using the .position() :
var overlayHeaderOffset = oH.position();

Javascript doesn't work correctly when css class is used more than once?

Previously, I asked how to center align an image (w/ dynamic width) within a div and someone replied with this code:
http://jsfiddle.net/WDzx4/6/
It's working correctly. However, when I try using the same class for another image, the other image is no longer vertically centered:
http://jsfiddle.net/b4Bbd/
You see, now, the 50x50 black image is slightly higher than it should be. I noticed that only the first image gets aligned correctly. If I add other images with a different width and height (using the same class) after that, they will be misaligned.
Could somebody help me find the problem as I'm not really familiar with javascript.
You need to wrap the JavaScript to do everything for all matching elements, instead of calculating the height for one and applying to all:
$('div.container_img img').each(function() {
var $img = $(this);
var h = $img.height();
$img.css('margin-top', +h / -2 + "px");
});
Try this: http://jsfiddle.net/timothyclifford/b4Bbd/7/

Categories