Skip to content

Instantly share code, notes, and snippets.

@matthewhudson
Created June 13, 2014 20:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewhudson/4f0edc810cb5e714c612 to your computer and use it in GitHub Desktop.
Save matthewhudson/4f0edc810cb5e714c612 to your computer and use it in GitHub Desktop.
Nifty background parallax effect (requires underscore.js)
# Note that when compiling with coffeescript, the plugin is wrapped in another
# anonymous function. We do not need to pass in undefined as well, since
# coffeescript uses (void 0) instead.
do ($ = jQuery, window, document) ->
# window and document are passed through as local variable rather than global
# as this (slightly) quickens the resolution process and can be more efficiently
# minified (especially when both are regularly referenced in your plugin).
# Create the defaults once
pluginName = "backgroundParallax"
defaults =
movementStrength: 15
# The actual plugin constructor
class Plugin
constructor: (@element, options) ->
# jQuery has an extend method which merges the contents of two or
# more objects, storing the result in the first object. The first object
# is generally empty as we don't want to alter the default options for
# future instances of the plugin
@settings = $.extend {}, defaults, options
@_defaults = defaults
@_name = pluginName
@init()
init: ->
# Place initialization logic here
# You already have access to the DOM element and the options via the instance,
# e.g., @element and @settings
movementStrength = @settings.movementStrength
height = movementStrength / $(window).height()
width = movementStrength / $(window).width()
$el = $(@element)
throttled = _.throttle((ev) ->
pageX = ev.pageX - ($(window).width() / 2)
pageY = ev.pageY - ($(window).height() / 2)
x = width * pageX * -1 - 25
y = height * pageY * -1 - 50
$el.css 'background-position', "#{x}px #{y}px"
, 35)
$('body').mousemove throttled
# A really lightweight plugin wrapper around the constructor,
# preventing against multiple instantiations
$.fn[pluginName] = (options) ->
@each ->
if !$.data(@, "plugin_#{pluginName}")
$.data(@, "plugin_#{pluginName}", new Plugin(@, options))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment