How to create a split image effect using JavaScript and CSS3

Raddy CSS, JavaScript Leave a Comment

This video will teach you how to create a split image effect that you see mostly on web sliders and modern websites like Apple, using JavaScript and CSS3.

The code will be available on this page soon.

HTML
<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>JavaScript Split Image Effect!</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <link rel='stylesheet' type='text/css' media='screen' href='css/styles.css'>
    <script src='main.js'></script>
</head>
<body>

    <div id="split">
        <img src= "/images/unsplash.jpg"/>
    </div>

</body>
</html>
CSS
#split {
    width: 850px;
    height: 500px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    perspective: 400px;
    cursor: pointer;
  }

#split img {
    height: auto;
    width: 100%;
    opacity: 0;
}

img {
    width: 100%;
    height: auto;
}

#split div {
  position: absolute;
  z-index: 1;
  background-repeat: no-repeat;
  transform: rotateY(-50deg) scale(0.5);
  opacity: 0;
  transform-origin: bottom;
  transition: all 0.6s cubic-bezier(0.71, 0.05, 0.09, 0.91);
}

#split.active div {
  opacity: 1;
  transform: rotate(0deg) translateY(0);
  transition-delay: 0.5s;
}
JavaScript
var Slice = function() {
    var sliceDiv = document.getElementById('slice');
    var gridX = 4;
    var gridY = 2;
    var w = sliceDiv.offsetWidth;
    var h = sliceDiv.offsetHeight;
    var img = document.querySelectorAll('#slice img')[0].src;
    var delay = 0.05;

    console.log(w, h, img);

    this.create = function() {
        for (x = 0; x < gridX; x++) {

            var width = x * w / gridX + "px";
            var div = document.createElement("div");
            document.getElementById('slice').appendChild(div);
            div.style.left = width;
            div.style.top = 0; 
            div.style.width = w / gridX + "px";
            div.style.height = h + "px";
            div.style.backgroundImage = "url(" + img + ")";
            div.style.backgroundPosition = "-" + width;
            div.style.backgroundSize = w + "px";
            div.style.transitionDelay = x * delay + "s";
            sliceDiv.classList.remove('active');
        } 
  
    }

    this.create();

    document.getElementById("slice").onmouseover = function() {mouseOver()};
    document.getElementById("slice").onmouseout = function() {mouseOut()};
   
    function mouseOver() {
        sliceDiv.classList.add('active');  
    }

    function mouseOut() {
        sliceDiv.classList.remove('active'); 
    }

}

window.onload = function() {
    var slice = new Slice();
};

Leave a Reply

Your email address will not be published. Required fields are marked *