Question

I've searched hours for code that will create a fade-in effect on an image when a user reaches its position, but my code continues to either work partially or not work at all. I'm thinking it could be my css positioning that is throwing it off but I could be wrong. If someone could point out my error this would definitely help me as well as clear up the subject for others with similar problems.

Here's the fiddle I'm trying to mimic(only with an image rather than a div): http://jsfiddle.net/tcloninger/e5qaD/

When I incorporated above fiddle code into my website, all the images with the "hide me" class would fade in at once, rather than one at a time as I reached them. So I found this fiddle to see if it would better detect element position. http://jsfiddle.net/moagrius/wN7ah/

This resulted in no images fading in at all. Here's the pieces of my code that I'm trying to use together:

Code to detect the location of .hideme class and make opaque when it is in the window:

$(document).ready(function() {

$.fn.isOnScreen = function(){

var win = $(window);

var viewport = {
    top : win.scrollTop(),
    left : win.scrollLeft()
};
viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + win.height();

var bounds = this.offset();
bounds.right = bounds.left + this.outerWidth();
bounds.bottom = bounds.top + this.outerHeight();

return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
};

$(window).scroll(function () {
    if($('.hideme').isOnScreen()){
        $('.hideme').animate({'opacity':'1'},500);
});

Example div of how my html is set up and where the .hideme class is:

<div id="two" class="page">
<img src="img/splithead.png" alt="divided attention" class="icons vandhcenter"/>
<div class="abs">
<img src="text/div2.png" alt="section two text" class="text hideme"/>     
</div>
</div>

In the case that the problem is positioning, here is excerpts of my css:

div.page
{
display:block;
height:100%;
position:relative;
width:100%;
}

img.icons
{
height:600px;
width:800px;
}

.vandhcenter 
{
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
}

img.text
{
float:left;
position:relative;
width:800px;
}

.hideme 
{
opacity:0;
}

In case all of this looks confusing in a list like this here's a jsfiddle link so you can see all of my code. There's no real output because I didn't upload all of my image files, but it may be easier to see the code. jsfiddle,net/uxB4D/

Was it helpful?

Solution

What you're describing sounds like "lazy-loading". There are quite a few plugins that do this already; for example: http://www.appelsiini.net/projects/lazyload

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top