Adjusting div height dynamically based on scroll

I know this is a pretty easy way to do it, but I can't find anything in my searches.

I have found many examples of going to a specific scroll position on the page and then animating the div to a different size, however I want to adjust the div max height based on the scroll location. Initially I would like the div's maximum height to be around 150px, and then when you scroll from 200px down the page to 400px down the page, I want the div's maximum height to decrease to 75px. Then, obviously, as you scroll through the backup, it gets bigger.

I cannot provide an example of what I have already tried as I am still trying to do this as I have no idea where to start.

Note: The size should be gradually adjusted using the scroll position.

+3


source to share


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);
})

      



You have a sample here: https://jsfiddle.net/keccs4na/

+7


source


You can 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 want to use CSS to initially set the height to 150px

.

+2


source


Try it.

$(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);
        }
    });

      

+1


source







All Articles