Tara Irvine
Tara Irvine

Reputation: 819

How to fix the position of a div when it gets to a certain point

I'm not 100% sure if the question title is accurate so I'm willing to change if someone can explain exactly what it is called that I want to do.

I have a div containing images and copy for each "project" under the first image, what I want to do is position:fixed the div when the first image of the project gets to a certain point, so far I have managed it when the page is scrolled right.

How it works

It check the left position of the div moving against the div fixed initially, then if it's close enough not closer than (fixedLeft+400), the classes swap, the original div that was stuck goes on it's merry way and the new one sticks.

It works great, although not throughly tested, I'll have to debug a bit but I'm hitting a dead end trying to get it to go back the way.

Here's my fiddle - big version = images are perhaps too big http://fiddle.jshell.net/tara_irvine/d5VdF/12/show/

and the fiddle part with code http://jsfiddle.net/tara_irvine/d5VdF/12/

The code has lots of stuff removed because my content is dynamic and everything (content and copy) is based around the hidden nav, so that could maybe be ignored.

Even if someone can talk me through the logic of how it should work that would help.

I really hope someone can help. Thanks very much

Upvotes: 2

Views: 303

Answers (1)

roryok
roryok

Reputation: 9645

adding a behaviour to each li element seems like an odd way to solve the problem. I'd rather set the first copy-container as fixed-copy initially, then have a single $(window).scroll in the $(document).ready and track the offset of it. Once it reaches a certain threshold, change the classes. This should be easier to reverse too.

UPDATE: This is working for me

$(document).ready(function(){
    $(window).scroll(function (){   
        var offset = $(".fixed-copy").offset().left;
        $(".fixed-copy").find(".offsetLeftGroupPrev").html(offset);     
        var next = $(".fixed-copy").parents("ul").next("ul.imgGroup").find(".copy-container");      
        var prev = $(".fixed-copy").parents("ul").prev("ul.imgGroup").find(".copy-container");  

        if(offset > next.offset().left){
            $(".fixed-copy").removeClass("fixed-copy");
            next.addClass("fixed-copy");
        }   

        if(prev!=null && prev.offset() != null){    
            if(offset < prev.offset().left){
                $(".fixed-copy").removeClass("fixed-copy");
                prev.addClass("fixed-copy");
            }
        }
   });  
});

Upvotes: 1

Related Questions