Interactive Background Parallax Effect With jQuery And CSS3

File Size: 1.98 KB
Views Total: 4880
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Interactive Background Parallax Effect With jQuery And CSS3

A minimalist interactive background parallax effect that utilizes jQuery and CSS3 to smoothly move your background image that reacts to user's cursor.

See also:

How to use it:

1. Add a position: absolute background image to your parallax element.

<div class="bg"></div>
.bg {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  z-index: -1;
  background: url("bg.jpg") no-repeat center center;
  background-size: cover;
  -webkit-transform: scale(1.1);
  transform: scale(1.1);
}

2. Put the needed jQuery library at the end of the document.

<script src="//code.jquery.com/jquery-2.2.2.min.js"></script>

3. The JavaScript (jQuery script) to active the interactive parallax effect on the background image when mouse moving.

var lFollowX = 0,
    lFollowY = 0,
    x = 0,
    y = 0,
    friction = 1 / 30;

function moveBackground() {
  x += (lFollowX - x) * friction;
  y += (lFollowY - y) * friction;
  
  translate = 'translate(' + x + 'px, ' + y + 'px) scale(1.1)';

  $('.bg').css({
    '-webit-transform': translate,
    '-moz-transform': translate,
    'transform': translate
  });

  window.requestAnimationFrame(moveBackground);
}

$(window).on('mousemove click', function(e) {

  var lMouseX = Math.max(-100, Math.min(100, $(window).width() / 2 - e.clientX));
  var lMouseY = Math.max(-100, Math.min(100, $(window).height() / 2 - e.clientY));
  lFollowX = (20 * lMouseX) / 100; // 100 : 12 = lMouxeX : lFollow
  lFollowY = (10 * lMouseY) / 100;

});

moveBackground();

This awesome jQuery plugin is developed by vajkri. For more Advanced Usages, please check the demo page or visit the official website.