javascriptcssparallax

how do parallax mouse move effect pure javascript


How can I realize a parallax effect like this example:

but without using jQuery, with pure javascript and only with an image?

$(document).ready(function(){
  $('#landing-content').mousemove(function(e){
    var x = -(e.pageX + this.offsetLeft) / 20;
    var y = -(e.pageY + this.offsetTop) / 20;
    $(this).css('background-position', x + 'px ' + y + 'px');
  });    
});
#landing-content {
 overflow: hidden;
 background-image: url(http://i.imgur.com/F2FPRMd.jpg);
 width: 100%;
 background-size: 150% 150%;
 background-repeat: no-repeat;
 max-height: 500px;
 border-bottom: solid;
 border-bottom-color: #628027;
 border-bottom-width: 5px;
}

.slider {
  margin-left: auto;
  margin-right: auto;
  overflow: hidden;
  padding-top: 200px;
  max-width: 1002px;
}

.slider img {
 width: 80%;
 padding-left: 10%;
 padding-right: 10%;
 height: auto;
 margin-left: auto;
 margin-right: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="landing-content">
    <section class="slider"> 
        <img src="http://i.imgur.com/fVWomWz.png"/>
            
    </section>
</div>

Note: like in the example, the element should move smoothly in the mouse direction.


Solution

  • You could update two custom properties depending on the clientX/clientY coordinate which control the position of a background, like in this proof of concept

    Codepen demo


    let dde = document.documentElement;
    dde.addEventListener("mousemove", e => {
      let ow = dde.offsetWidth; 
      let oh = dde.offsetHeight; 
      dde.style.setProperty('--mouseX', e.clientX * 100 / ow + "%");
      dde.style.setProperty('--mouseY', e.clientY * 100 / oh + "%");
    });
    :root {
      --mouseX: 50%;
      --mouseY: 50%;
    }
    
    body {
      padding: 0;
      inline-size: 100%;
      min-block-size: 100dvh;
      overflow: hidden;
      background-size: auto 250%;
      background-position: var(--mouseX) var(--mouseY);
      background-repeat: no-repeat;
      background-image: url('https://www.thesprucepets.com/thmb/uQnGtOt9VQiML2oG2YzAmPErrHo=/5441x0/filters:no_upscale():strip_icc()/all-about-tabby-cats-552489-hero-a23a9118af8c477b914a0a1570d4f787.jpg');
    }
    <body></body>

    In this example I've used an image covering the full viewport in height but really large. At the initial state the background is centered.

    In JS on mousemove event you get the coordinate of the mouse (eg. clientX or clientY) and set a CSS custom property (--mouseX/--mouseY) with that value, which is used for background positioning.