supersize
supersize

Reputation: 14783

change id of button depending on current viewed div

ive a problem which is driving me crazy. im trying to explain... i have a very long scrolling page with about 10 divs, one below the other (no space between). at the bottom of the viewing port is a button with an id and a position: fixed. when i scroll up or down the button is fixed while the divs move up or down. i want to have different id's on the button depending on which div layer is in the viewing port. that means if one divlayer fills over 50% of the available space the href of the button should change... i tried the inview.js, but the problem is, that 2 divs at the same time have the inview class...

my current code:

$('#div4, #div5, #div6').bind('inview', function (event, visible) {
        if (visible == true) {
        $(this).addClass("inview");

        } else {

        $(this).removeClass("inview");
        }
    });





var $div4 = $('#div4');

if($div4.hasClass("inview")){
    $('#button1').attr('id', 'button2'); 
  }

you see, every div which is in the viewport the button gets a new id. has anyone of you a solution? thanks ted

Upvotes: 0

Views: 259

Answers (1)

lucuma
lucuma

Reputation: 18339

You can try to remove the inview class before adding it.. Something like this:

var $divs = $('#div4,#div5,#div6';
$divs.bind('inview', function (event, visible) {
        $divs.not(this).removeClass("inview");
        if (visible == true) {
          $(this).addClass("inview"); 
        }
     });

Another suggestion is to use the Waypoints plugin and fire when the div crosses the 50% mark.

The only difficult part is that depending on the direction you'll need to select the current div or the one above.

Plugin: http://imakewebthings.com/jquery-waypoints/

Demo: http://jsfiddle.net/lucuma/nFfSn/1/

Code:

 $('.container div').waypoint(function (direction) {
        if (direction=='up')
            alert('hit ' + $.waypoints('above')[$.waypoints('above').length-2].id);
        else
            alert('hit ' + $(this).attr('id'));  
    }, {
        offset: $.waypoints('viewportHeight') / 2

});

Upvotes: 1

Related Questions