Reputation: 488
I am working for a designer who has created a GIF that only has one cycle of an animation. This gif actually appears about halfway down a scrolling page, i.e it starts off screen, so by the time you get there the animation has already fired.
I have created two versions of this GIF, one in it starting state, and the animated one.
I want it so that when the user scroll down the page, the animated GIF loads at the appropriate time (i,e when its on screen), and then loads the animated version into the DOM which then plays
I have tried using scrollspy, but this only delays the showing of the icon, and not the actual loading, so when it appears as the user scrolls down the animation has already been and gone.
Is it possible? My common sense is telling me that this is not even worth the dev time as its not even that important an animation, and should just be on a loop like most normal GIF's but.. well.. thats designers for ya!
All encapsulated in a
Thanks in advance for any assiatance
NOTE : Using the answer below, this was my working piece of code (needs tidying, and the plugin was installed)
jQuery(document).ready(function($) {
window.onscroll = function() {
if($("#printer_animated_image").visible()) { //this determines if the element is visible
$("#printer_animated_image").attr("src", "images/modules/how_it_works/step_4_b.gif"); //this sets the image source
}
}
});
</script>
Upvotes: 1
Views: 3548
Reputation: 130810
First of all, it's better to preload that animated gif: https://stackoverflow.com/a/14390213/104380
Then you must check if DOM element where the GIF is supposed to be is visible to the user. you can simply check this elm.getBoundingClientRect().top < 0
on every scroll and then inject that GIF image where it should be.
var elm = getElementById('#elm');
$(window).on('scroll.reached', placeLoadingGIF);
function placeLoadingGIF(){
if( elm.getBoundingClientRect().top < 0 ){
var img = new Image();
img.src = 'step_4_b.gif';
elm.appendChild(img);
$(window).off('scroll.reached');
}
}
Something of this sort.
Upvotes: 1
Reputation: 157
This is what you are looking for
You can download the jquery plugin from that site then write an onscroll handler like this:
window.onscroll = function() {
if($('#element').visible()) { //this determines if the element is visible
$('#element').attr("src", "step_4_b.gif"); //this sets the image source
}
}
In the above #element needs to be replaced with the ID of the image.
Also if you don't want to install a plugin just for a single image JQuery has a built in feature that is similar, but not as complex:
window.onscroll = function() {
$('#element:visible').attr("src", "step_4_b.gif");
}
Which does the same thing, but if the image has been made invisible with CSS it will still be considered visible in this version.
Upvotes: 1