0

In the fiddle you will see at the center of the page a DIV that contains text next to an img.

When I scroll down/up I need to effect with jquery/javascript only the div who's the closest to the navbar-below. all the divs as the same class so I effect them all-not what I need

For example:

what I am trying to achieve : when I scroll down,the closest div to the navbar(yellow bar) will be painted(the div) green,so if I scroll down and the navbar "collapse" with the div with will paint in green, and when he passes him and "disapper" it will go back to original color and the next div will paint in green. is it possible?

Here's the JS FIDDLE

When I referred to div I meant this section :

<div class="x" id="inside_center">
    <div class="left_side" id="left_inside_center">sddsadasasdsadLorem </div>
    <div class="right_side" id="right_inside_center"><img src="http://img-9gag-lol.9cache.com/photo/a7KwPAr_460s.jpg"></div>
</div>

EDIT:

UPDATED JSFIDDLE :

http://jsfiddle.net/nnkekjsy/3/

I added my jquery,as you can see it works only for the first one,and then stuck.. i need to "pass" it along the others div below him when the are getting to the same point. any ideas? :

$(document).ready(function() {
   $(window).scroll(function() {
       var scrollVal = $(this).scrollTop();
       var navHeight = $("#div_menu").outerHeight();
        if ( scrollVal > 55) {
            $('#left_inside_center').css({'position':'fixed','top' :navHeight+'px'});
        } else {
            $('#left_inside_center').css({'position':'static','top':'auto'});
        }
    });
 });
roi m
  • 13
  • 4

1 Answers1

0

Have you tried use the first-of-type to select the top div, if i understand what your trying to do.

CSS3 selector :first-of-type with class name?

An other solution would be to check the position of the div and the nav bar and pick the closest one.

$(".left_side").each(function () {
    //compare scroll with div
    if(window.scrollTop() = $(this).position.top())
    {
        //do something
    }
});

I know the position and the scroll won't be the same value but you can play with the condition to put some range.

Edit :

I think this is what you want. The navHeight and the height variable should be outside the window.scroll function as they never change :

$(window).scroll(function() {
   var scrollVal = $(this).scrollTop();
   var navHeight = $("#div_menu").outerHeight();
   var height = parseInt($(".right_side").css("height").split("px")[0]);

   $(".left_side").css({'position':'static','top':'auto'});
    $(".left_side").filter(function( ) {    
        return $(this).position().top - 10 < scrollVal && $(this).position().top  + height > scrollVal;  
    }).css({'position':'fixed','top' :navHeight+'px'});

});

Working fiddle :

http://jsfiddle.net/nnkekjsy/6/

Community
  • 1
  • 1
Mathieu Labrie Parent
  • 2,598
  • 1
  • 9
  • 10