Search code examples
javascriptjquerycollisionoffset

Jquery change div based on another div's position


Let me start of by saying, I'm just now learning JS and Jquery, so my knowledge is very limited.

I've been looking around for 2 days now, and tried all sorts of combinations. But I just can't get this to work.

Below is an example of the layout

enter image description here

I'm looking for a way to trigger an event when div 1 is X px from the top of the screen. Or when div 1 collides with div 2.

What I'm trying to accomplish is to change the css of div 2 (the fixed menu) when div 1 is (in this case) 100px from the top of screen (browser window). Alternatively, when div1 passes div2 (I'm using responsive design, so the fixed height from top might become a problem on smaller screens right? Seeing as the header for example won't be there on a hand held.). So maybe collision detection is better here? Would really appreciate some thoughts and input on this matter.

Another issue is, div2 has to revert back to is previous css once div1 passes it (going back (beyond the 100px)).

This is what I have but it has no effect

    $(document).ready(function() {

    var content = $('#div1');
    var top = $('#div2');

    $(window).on('scroll', function() {
        if(content.offset().top <= 100) {
            top.css({'opacity': 0.8});
        }else{
            top.css({'opacity': 1});
        }
    });
});

Solution

  • I am not sure of the reason but $("#content").offset().top was giving a constant value on console. So I added window.scrollTOp() to check its distance from top, here is how it works,

    $(document).ready(function() {
    var top = $("#menu");
        $(window).on('scroll', function(){
            if(($('#content').offset().top - $(window).scrollTop()) <= 100){
                top.css({'opacity': 0.4});
            }else{
                top.css({'opacity': 1});
            }
        });
    });
    

    And DEMO JSFIDDLE....