web dev & more!

Scrolling Shadows

Published: December 9, 2013

This plugin is derived from the same idea that was posted here, except in a much simpler form and using HTML5 to control the shadow attributes.

The jQuery looks like this:

/* 12/5/13 Dylan Hildenbrand */
function calculateShadow(object){
  var blur = object.data("blur");
  var spread = object.data("spread");
  var xpos = object.data("xpos");
  var dir = object.data("direction");

  var ypos = null;
  if(dir=="down"){
    ypos = (jQuery(window).scrollTop() / object.data('speed'));
  }
  else {
    ypos = -(jQuery(window).scrollTop() / object.data('speed'));
  }

  object.css("box-shadow", xpos+"px "+ypos+"px "+blur+"px "+spread+"px rgba(0, 0, 0, 0.5)");
}

jQuery(document).ready(function(){

  var object = jQuery("#object");
    calculateShadow(object);

  jQuery( window ).resize(function() {
    calculateShadow(object);
  });

  jQuery(window).scroll(function () {
    calculateShadow(object);
  })
});

The HTML:

<div id="content" class="site-content" role="main">
<!-- Elements on object set parameters for box shadow
data-direction: move shadow up or down
data-blur: shadow blur
data-spread: shadow spread
data-speed: speed of shadow movement; less means faster
data-xpos: x-position of shadow
data-ypos: y-position of shadow
-->
<div id="object" data-blur="10" data-spread="3" data-xpos="10" data-ypos="20" data-speed="8" data-direction="down">
obj
</div>
</div><!-- #content -->

Archived Comments

These comments have been imported from a previous commenting system, for the sake of posterity. If you left a comment using the old system and would like to have it removed, please get in touch with me using this form.