Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adjust div height dynamically based on scroll

I know there's a pretty simple way of doing this, but I can't seem to find anything in my searches.

I've found lots of examples of getting to a certain scroll location on the page and then animating a div to a different size, however I want to adjust a div's max height depending on the scroll location. Initially i'd like the div max-height to be about 150px, and then as you scroll from around 200px down the page to 400px down the page, I want the max-height of the div to decrease to 75px. Then obviously as you scroll back up, it gets larger.

I can't provide an example of what I've tried already, as I'm yet to attempt it as I have no idea on where to start.

Note: The size should gradually adjust with the scroll position.

like image 644
BN83 Avatar asked Jun 23 '15 14:06

BN83


3 Answers

I'm not sure if I understood your problem, but when I did I came out with this :D

$(window).scroll(function(){
  var scrollTop = $(window).scrollTop();
  if(scrollTop < 200){
    maxHeight = 150;
  }else if(scrollTop > 400){
    maxHeight = 75;
  }else{
    maxHeight = 150 - 75 * (((scrollTop-200) * 100)/200)/100;
  }
  $('#thediv').stop().animate({'max-height': maxHeight+"px"}, 500);
})

Here you have a sample : https://jsfiddle.net/keccs4na/

like image 89
Babesh Florin Avatar answered Sep 28 '22 18:09

Babesh Florin


You could try this:

$(window).on('scroll', function() {
    var scrollTop = $(window).scrollTop();

    if (scrollTop >= 200 && scrollTop <= 400) {
        $('#divID').stop().animate({height: "75px"}, 250);
    } else {
        $('#divID').stop().animate({height: "150px"}, 250);   
    }
});

Note: You'll want to use CSS to initially set the height to 150px.

like image 37
NightOwlPrgmr Avatar answered Sep 28 '22 18:09

NightOwlPrgmr


Try this.

$(window).on('scroll', function () {
    var v = $(window).scrollTop();
    if (v > 200) {
        $('#id-of-div').css({"height": "75px","max-height":"75px"});
    }
    else {
        $('#id-of-div').css({"height": "150px","max-height":"150px"});
    }
});

EDIT:

   $(window).on('scroll', function () {
        var v = $(window).scrollTop();
        if (v > 200) {
            $('#id-of-div').animate({"height": "75px","max-height":"75px"},500);
        }
        else {
            $('#id-of-div').animate({"height": "150px","max-height":"150px"},500);
        }
    });
like image 43
Varun Avatar answered Sep 28 '22 17:09

Varun