Progressive loading codesnip not quite understood - javascript

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.

Related

Smooth way to replace background-image

I’m quite new to jQuery and JS and been asked to write a script that will be loading background-image progressively - I mean that low quality image should appear immediately and when full size image is loaded should replace the small one.
I found some tips how to do something similar by layering <img /> on top of background-image however in my case i have to deal with background-image only, so I have made this:
$('.img-loader').each(function(){
var box = this;
var smallImg = $(this).attr('style');
var bigImg = smallImg.replace('.jpg)', 'big.jpg)');
var imgUrl = bigImg.replace('background-image: url', '');
var imgUrlS = imgUrl.replace(/[{()}]/g, '');
console.log(imgUrlS);
$('<img/>').attr('src', imgUrlS).load(function(){
$(this).remove();
$(box).attr('style', bigImg);
});
})
The script basically does the job but in that moment when the image gets replaced there is a quite noticeable ‘shake’.
Any ideas how to make transition smoother or anyone knows what causing this 'shake'?
Edit: As suggested I'm adding a markup snipped of where script has to be applied.
<div class="about__section__bgimage img-loader"
style="background-image: url(<?php echo $contentBlock->imageurl ?>)"></div>
I suggest you create two separate elements with the same size, overlapping each other, with position: absolute; make one of them visible with the original bg image (using opacity: 1). The second one invisible (using opacity:0)
Once the higher quality image is completely loaded, set the opacity of the original image to 0 and the new image to 1.
use a css transition on the opacity property to make the opacities change smoothly.
you have to use animation for this. Use any of them according to your scenario enjoy it !!!
https://daneden.github.io/animate.css/

Replace background image with GIF once loaded

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.

How to apply blur effect to background image in Blogger?

I've been trying to add blur effect to my posts but only thing that gets blurred is the main post content (pic: http://i.gyazo.com/9d94d2be5dc3f3ada982564aa212336e.jpg). Any idea how to target the background-image, instead of the content?
The code I am using at the moment is:
<script type="text/javascript">
var image = document.querySelector('.post-body img').src;
var target = document.body;
target.style.backgroundImage = "url(" + image + ")";
target.style.backgroundSize = "cover";
document.body.style["background-attachment"] = "fixed";
</script>
I have a odd feeling that you need to make the actual background image into standalone element but I have no idea how.
Also, is there a possibility I could add Blur.js into blogger or is it only for Wordpress? If yes, I'd like to know how?
Thanks in advance.
I worked on this and saw this question. So here's a suggestion.
<script type="text/javascript">
function showBackground() {
document.getElementsByClassName('body-fauxcolumn-outer')[0].style.backgroundImage = "url('http://backgroundImage.jpg')";
document.getElementsByClassName('body-fauxcolumn-outer')[0].style.backgroundPosition = "center center";
document.getElementsByClassName('body-fauxcolumn-outer')[0].style.backgroundRepeat = "no-repeat";
document.getElementsByClassName('body-fauxcolumn-outer')[0].style.backgroundAttachment = "fixed";
document.getElementsByClassName('body-fauxcolumn-outer')[0].style.webkitFilter = "blur(5px)";
}
window.onload = showBackground();
</script>
Explanation
As I used the simple template at this time, I noticed that the standard template has a class named body-fauxcolumn-outer which is used to set the background color.
So I adapt my answer here to answer this question.
I just added the following to fix the blur as you can see in the image bellow.
document.getElementsByClassName('body-fauxcolumn-outer')[0].style.webkitFilter = "blur(15px)";
You could try use this CSS 3 tag:
filter: blur(5px);
You can see the mdn documentation here: https://developer.mozilla.org/en-US/docs/Web/CSS/filter
You can do this on Blogger without using any JS or CSS.
Upload your image into a Blogger post as if you want to put it in an article.
Copy the URL of the image and paste it into the body css like so:
body {
background-image: url('YOUR IMAGE URL HERE');
}
Replace the /s-1600/ part of the url with /s1600-fcrop64=1,000f0000ffceffff:Soften=1,20,0/
Note: You can adjust the radius of the blur by fiddling with the second number after Soften=(in the case above, 20).
The advantage of doing this is it's lighter on code and completely compatible with every device and browser that is capable of loading an image!

Wait for image added to CSS to load - JQuery

I have an image and I want to draw on it. To do that, I use jQuery to hide the image:
$("img").hide();
And then I create a canvas and put it in the same div with id drawing in the html. I then set the background of the canvas to be the same as the img src for the image I hid. This makes it look like an image but now it is actually a canvas with the image as it's background. I do this by:
$('#drawing > canvas').css('background-image','url('+$(".image img").attr('src')+')');
context.canvas.width = $("img").width();
context.canvas.height = $("img").height();
The issue I am having is that sometimes, the image isn't displayed in the canvas and the canvas is not the size of the image. I think it's probably because of some loading issue. How can I wait for the canvas to have the image displayed in the background for sure? Thank you
Edit: Note that in the DOM, the canvas always has the right src. It just doesn't display it
Edit 2: Here's the JSfiddle. Here, everything seems fine but I have a lot more going on in my code including fetching stuff from the server so it's slower there. Hope this helps you guys to understand the problem: http://jsfiddle.net/wL3ezLke/2/
Thanks again
You need to use:
$(function(){
// Code executed once the DOM is loaded.
});
Official documentation:
https://api.jquery.com/ready/
If I understand correctly your problem is knowing when the image loaded (from what you describe it could be a lot of other problems though).
To test if an image has loaded it's pretty simple.
var $img = $('#hiddenImg');
if ($img[0].complete) doCanvasStuff();
else {
$img.on('load', function(e) {
var $canvas = $('#drawCanvas');
$canvas.css({width: $img.width(), height: $img.height()});
//you can go ahead with the background image, but this is preferable
var ctx = $canvas[0].getContext("2d");
ctx.drawImage(img,0,0);
}
}
This should make sure you canvas loads an image only after it was loaded, or do canvas stuff right away if image was loaded, fiddle
Change
$('#drawing > canvas').css('background-image','url('+$(".image img").attr('src')+')');
context.canvas.width = $("img").width();
context.canvas.height = $("img").height();
to
context.canvas.width = $("img").width();
context.canvas.height = $("img").height();
$('#drawing > canvas').css('background-image','url('+$(".image img").attr('src')+')');
so the height and width are set before the image goes into the background.

preload image then change background javascript

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

Categories

Resources