Skip to content Skip to sidebar Skip to footer

JQuery Image Height Change On Scroll

I have a fixed header on my website, and im trying to make the logo image resize as you scroll down to a certain point, then increase as you scroll back up. On scrolling down the i

Solution 1:

you need to get the imageHeight and marginHeight outside the scroll event like this

//get original height and margin-top outside scroll     
var imageHeight = parseInt($('.headlogo').css('height')),
    stopHeight=imageHeight / 2,
    marginHeight = parseInt($('.navbar').css('margin-top'))
    stopMargin=marginHeight/2;

$(window).scroll(function(e) {
    var windowScroll = $(window).scrollTop(),
        newMargin = marginHeight - windowScroll,
        newHeight = imageHeight - windowScroll;
    if(newHeight>=stopHeight){
        $('.headlogo').css("height", newHeight);
        $('.navbar').css("margin-top", newMargin);
    }
    else{
        $('.headlogo').css("height", stopHeight);//if it scroll more set to stopHeight
        //you can also set $('.navbar').css("margin-top", stopMargin); 
    }
});    

http://jsfiddle.net/xhLhY/


Solution 2:

Well just to make some fun out of this question, consider this

 size = Math.PI/2/1000
 height(x) = maxHeight/2( 1 + Math.cos(x/size))

So when scroll is 0 it will be just maxHeight and when x will be 1000 it will be just maxHeight/2, and it would be maxHeight again at 2000 and so on.

function imgSize(maxHeight, cycle) { 
   var s = Math.PI/2/cycle 
   return function(x) { return maxHeight/2(1 + Math.cos(x/s) }
} 

var img = $('img.headlogo')
  , maxHeight = img.css('height')
  , resize = imgSize(maxHeight, 1000)

$(window).on('scroll', function(e) {
   var x = $(document).scrollTop()
   img.stop().animate({ height: resize(x) }, 500)
})

Solution 3:

If you need numeric properties you must use:

imageHeight = $('.headlogo').height();

otherwise your imageHeight is NaN and you can not use:

newHeight = imageHeight - windowScroll

Solution 4:

A JS fiddle like this will change your css class upon scrolling, so you can have one class with the image set to say 100% and one set to 50%, so as you scroll the JS will change CSS classes to the size you'd like.

$(function(){

var images = $(‘.yourClass’)
scrolledDistance = $(document).scrollTop()
 windowHeight = $(window).height()
 inView = scrolldDistance + windowHeight

 $(images).each(function(){
 var position = $(‘this’).position()
 topOffset = position.top
  if (inView < = topOffset ){
  $(this).css({‘opacity’:’0′}) 
  }
  })



$(window).scroll(function () { 
//update scrolled distance
scrolledDistance = $(document).scrollTop()
$(images).each(function(){
var position = $(‘this’).position()
topOffset = position.top
if (inView < = topOffset ){
$(this).animate({‘opacity’:’0′},500)
}
})
})

})

Post a Comment for "JQuery Image Height Change On Scroll"