Im changing the background image with the following code inside a script tag. This is causing a whiteflash when the background changes, all my pages are ajax. I cant just pick a background color like the background as im also using this on profiles page and each profile has a different background.
is it possible to preload the image then change the background to stop the whiteflash? thanks
$('body').css('background-image', 'url(../images/waves.jpg)');
$('body').css('background-attachment', 'fixed');
$('body').css('background-size', 'cover');
You could load a hidden image and change it when the image finishes loading, like this:
function preloadImage(source, destElem) {
var image = new Image();
image.src = source;
image.onload = function () {
var cssBackground = 'url(' + image.src + ')';
$(destElem).css('background-image', cssBackground);
};
}
Usage:
preloadImage('images/waves.jpg', 'body');
EDIT: Wrapped the code inside a function.
EDIT 2: Here is an example without the background flash while changing. http://jsbin.com/admmx/4/edit?html,css,js,output.
You can preluad image using Image() object.
var newImg = new Image();
newImg.src = "img2.jpg";
$('body').css('background-image', 'url('+ newImg.src +')');
I don't know if it would suit you, but I would use wrapper for the background and wrapper for the content. That way I can animate the change for my background without too much worry about the rest of the page.
If you know the pictures upfront you can use CSS classes to change them smoothly.
<body>
<div id="bg-wrapper" style="position: absolute; left: 0; top: 0"></div>
<div id="content-wrapper"></div>
</body>
of course I would write some code to look after re-sizing the browser window.
Here is an example fiddle
Related
I'm working on my first website and I want to create an HTML button and put an image on it.
But the image has the wrong size and I am looking for a way to scale the image before putting it on the button. That's how I tried it:
function setImg(){
var img = new Image(200,200);
img.src = "imgs/youtubeImg.png";
img.style.width = 100;
img.style.height = 100;
document.getElementById("youtubeButton").style.backgroundImage = img;
}
I don't know why it isn't working. I don't know if that is important, but this function is called after the button was created.
Hope you can help me, Thanks.
EDIT:
Method: appendChild:
Thats how it looks like with that function
But I want to let the img fit in this button:
But that only works if the image is the background image of the button.
Please try this instead,
Using appendChild() to add a image.
function setImg(e){
e.classList.add("active")
var img = new Image(200,200);
img.src = "https://images.unsplash.com/photo-1530103043960-ef38714abb15?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60";
img.style.width = "180px";
img.style.height = "70px";
document.getElementById("youtubeButton").textContent= "";
document.getElementById("youtubeButton").appendChild(img);
}
button{
padding:20px 30px;
}
button.active{
padding:0;
margin:0;
}
<button id="youtubeButton" onclick="setImg(this)">Youtube Button</button>
OP's solution moved from question to an answer:
I found the solution. You can just set the background size, so it scales the image automatically.
If you're setting the background image via css (as opposed to just appending it to the button which iou can also do) then you need to set the background-size attribute, look it up for details
I am using lazysizes for lazy image loading. It's working fine, but I was asking myself if it is possible to load the images in the background and replace the src attribute after the real image is fully loaded.
The problem I am facing right now is, that the src attribute is replaced with the real image when visible, but on slow internet connections, the image slowly loads from top to bottom.
I would rather wait until the image has loaded in the background and then replace the src attribute to prevent the effect shown in the screenshot below.
Do I have to use another library or can I arc hieve this with lazysizes?
Thanks in advance!
You can load an image with this code:
function loadImage(url, callback) {
var img = new Image();
img.onload = callback;
img.url = url;
}
Then on callback set your image url:
var url = "http://path.to/my/image.jpg";
loadImage(url, function() {
document.getElementById("myimg").src = url;
});
Answering my own question:
You can use the class .lazypreload to achieve this effect.
I am currently working on making an element progressive load so make the loading of hero banners more fluent, I came by this code example:
Codepen
The one I can't seem to understand is how the placeholder image is being switched to the original image.
The javascript does not seem to refer to original image at all?
So how does it render it?
I am currently getting a white screen when I use the javascript, which makes sense as the blurred image becomes more opacity =1 =>
$(function(){
$('.progressive-image').each(function(){
var image = new Image();
var previewImage = $(this).find('.loadingImage');
var newImage = $(this).find('.overlay');
image.onload = function(){
newImage.css('background-image', 'url(' + image.src + ')');
newImage.css('opacity', '1');
console.log('complete');
};
image.src = previewImage.data('image');
});
});
So how does this codepen blen the original image in and the blurred image out?
the tag which newimage finds does not contain the image? so even more confusion?
This is a little confusing but the code doesn't actually remove the old image. It inserts a new image into <div class="overlay"></div>, which overlays the 'loading' image in <div class="loadingImage"></div>.
Look at your Elements tab in inspector and you'll be able to see both of these.
How does this work?
More specifically the script grabs the 'full res' image url from the data-image tag in the loading-image div.
<div
class="loadingImage"
style="background: url('https://res.cloudinary.com/sourcetoad/image/upload/v1483582294/frog-2-sm_zjphps.jpg')"
data-image="https://res.cloudinary.com/sourcetoad/image/upload/v1483582295/frog-2-lg_vahxhg.jpg">
</div>
It grabs the data-image with:
image.src = previewImage.data('image');
Then it inserts it as a background image into the overlay div with:
newImage.css('background-image', 'url(' + image.src + ')');
It's kind of a funky example to look at, I got a bit lost in it as well.
newImage.css('background-image', 'url(' + image.src + ')');
This line of code sets the image on the <div class="overlay"></div>
Overlay is actually the real image, not the blurred image.
The Blurred Image is set with an inline style on <div class="loadingImage>
I have to admit I'm not a huge fan of what this codepen is doing, but that's how it is working.
One tip for picking something like this apart, start commenting out javascript lines to see how it works before the JS takes over.
I hope this helps.
I am facing a bit of an issue and cant seem to find a solution. I have a section tag
<section class="background-gif"></section>
This simply loads a background image
.background-gif {
background: url(../images/image.gif) no-repeat top;
background-size: 100%;
}
Straightforward enough. Problem is, the gif that is being loaded is 5MB as it has a lot of animation. This is causing the page load to be mega slow. I can't use a standard preloader, to do with requirements.
Instead, I thought I would give something like this a go https://medium.com/front-end-hacking/how-to-optimize-image-loading-on-your-website-855020fb41ae
However, my IDE does not seem to like this code, I think it is ES6? So I essentially trying to do something similar. My thought is to replace the above CSS so it initially displays a static image. And then in the background, the gif can load, and once loaded, replace the static image.
I have seen examples where an Image Object is used, something like this Dynamically replace image src after the page loaded and the image is completely downloaded
I cant however find anything that does this with background images.
How would I go about replacing the static background once the main gif has fully loaded?
Thanks
By giving the section.background-gif a placeholder image(in your case it can be a minified image from the GIF image that you want to load) , and give it a data-src attribute containing the path/link of the desired GIF image, then using JavaScript we'll load the GIF image based on the data-src attribute of the section.background-gif element, and when it loads we'll assign its src attribute to the background-image property of the section.background-gif element.
Here's a runnable snippet to illustrate:
In the snippet, I'm using a placeholder image from placeholder.com website that initially appears as the background, then I load a random GIF image from Google. The snippet may not work as expected due to some restrictions(as the snippets are sandboxed), so try it in your project it should work, just don't forget to replace the image links with yours.
// referencing the section element, and creating a new Image object.
var section = document.getElementsByClassName('background-gif')[0],
img = new Image();
// assign the data-src to the img variable src.
img.src = section.getAttribute('data-src');
// adding a 'load' event listener in which will change the section's background image when the img is loaded.
img.addEventListener('load', function() {
// the img is loaded, assign its src attribute to the section.
section.style.backgroundImage = 'url("' + this.src + '"';
// just for testing, not required.
console.log('The image has been loaded.');
});
section {
/* just for the demo */
height: 100vh;
}
.background-gif {
/* change the url to your image link */
background: url("https://via.placeholder.com/350x350") no-repeat top;
background-size: 100%;
}
<!-- don't forget the data-src to point to the large GIF image you want to set as a background -->
<section class="background-gif" data-src="http://cosmicweb.uchicago.edu/images/mov/s02_0.gif"></section>
Hope I pushed you further.
You can try preloading images. Preloading an image as an object will allow for linked event listeners including "onload". Let's try this....
window.addEventListener('load',init);
function init(){
var image = new Image();
image.src = 'https://images.unsplash.com/photo-1530482817083-29ae4b92ff15?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=44f4aebbd1e1371d5bf7dc22016c5d29&auto=format&fit=crop&w=700&q=60';
image.addEventListener('load',function(){
alert('image loaded');
document.body.style.background = 'url('+image.src+') no-repeat top';
});
}
Let me know how it goes with a larger image. I'm curious.
Okay so I've successfully managed after a couple of hours to call over an image using HTML localStorage system but I now have one problem with the called over image.... I can't dictate where it goes..... It just sits at the bottom of the page as the code is purely javascript..... I've tried putting it in a div and changing its position but it won't budge any suggestions.... heres the code thats calling the image across:
window.onload = function() {
var picture = localStorage.getItem('img');
var image = document.createElement('img');
image.src = picture;
document.body.appendChild(image);
};
How can I edit the position on the page as well as the hight etc......................? Any help appreciated!
You're appending the image to the document body, so likewise, it's going to be added to the bottom of the page.
You can set the properties of image.style to change the image's CSS properties such as height (image.style.height) and width (image.style.width).
To position it elsewhere on the page, you can change it's display properties
image.style.position = "absolute"; //(for example)
image.style.top = "50px"; //drops the image down 50px from the top of the page
Or, you can add it to a different part of the DOM altogether:
document.getElementById('ID_OF_YOUR_DIV').appendChild(image);
Hope this helps.