Code Blog

Displaying 1-1 of 1 result.
2016/04/26 Javascript,Yii

I had read about how to do a parallax effect for my background image (so effectively 1 layer parallax effect). I means that the background image slowly moves along as I scroll the text on my blog. In my case the background moves with 1/5 of the speed of the web page scrolling.

However I ran into some troubles when I happened to write too long post (i.e. many photos in posts quickly adds up in height). I had added some margin by using a tall background image in order to avoid this, but that was just a quick hack, and finally that just didn't seem to be able to solve it. 

Actually I would like the image to wrap around once it runs out of pixels to cover the whole web page window. I guess the setting the CSS background property to "repeat-y" and then use a javascript call to update the height as I scroll should do the trick but I opted for another solution.

 I decided to create 2 images that are shifted half-way in Y direction and swap between them as I scroll down. 

Illustration of switching between the two background images. One good tips I found is to use the "offset" filter in Photoshop and enter a 50% vertical offset and then re-save the image.

.bg
{
  background-position: 50% 0;  
  position: fixed;
  width: 1000px;
  height: 2000px;
  bottom:0;
  top:0;
  left:0;
  z-index: -1;	
}

.bg1 
{
  background-image: url('images/bg1.jpg');
}

.bg2 
{
  background-image: url('images/bg2.jpg');
}

I added a div at the top of the web page: <div class="bg bg1"></div>

$(window).scroll(function(e){
  parallax();
});
function parallax(){
  var scrolled = $(window).scrollTop();
  var imageheight = 2000;
  var bgscroll = scrolled*0.2 % imageheight;

  if ( bgscroll >= imageheight/2 ) {
  	$('.bg').removeClass('bg1').addClass('bg2');
  	$('.bg').css('top',imageheight/2-bgscroll+'px');
  } else {
  	$('.bg').removeClass('bg2').addClass('bg1');
  	$('.bg').css('top',-bgscroll+'px');
  }
}

I can then use the CSS class property to switch between background images for the bg div element.

When should the switch happen to the 2nd image? When half the first image has been scrolled up and out of sight. I therefore check for the background image scroll There is a half image height offset for the 2nd image. The image needs to be at least twice at high as the web browser window inner height (not incl toolbars/scrollbars). Please note the image dimension I have used is 1000 x 2000px for this example (width x height) and these values need to be changed for the code to work correctly with other dimensions.