Search code examples
javascriptjqueryscrolldom-eventsoffset

jQuery function that returns when a div touches another div upon scroll


how can I give an alert when one div hovers over another div upon scroll? here is a working example, http://jsfiddle.net/uprosoft/Ek5Gy/267/

I cant find a jQuery code to go after though in-order to give an alert.

Code:

HTML

<div id="container">
<div id="div1">test</div>
<br>
<div id="div2"> another test</div>
</div>

CSS

#div1{
background: green;
position: fixed;
        width: 100%;
}
#div2{
background: yellow;
position: relative;
width: 100%;
margin-top: 100px;
}
#container{

height: 1000px;

}

JQUERY ???

/* what jquery code goes here? to alert when the yellow div touches the green div upon scroll? */

Solution

  • Something like that should work:

    $(window).scroll(function() {
        var div1 = $("#div1");
        var div2 = $("#div2");
        var div1_top = div1.offset().top;
        var div2_top = div2.offset().top;
        var div1_bottom = div1_top + div1.height();
        var div2_bottom = div2_top + div2.height();
    
        if (div1_bottom >= div2_top && div1_top < div2_bottom) {
            // overlapped
        }
    });​
    

    DEMO: http://jsfiddle.net/Ek5Gy/280/