This code snippet creates an eye-catching image glitch effect using JavaScript. It combines CSS and JavaScript to manipulate the appearance of an image on a webpage. The main functionality revolves around dynamically creating multiple glitch boxes and applying random positioning, size, and background-position to each box at regular intervals.
The glitch effect adds a visually striking and dynamic element to the webpage, making it more engaging and visually appealing for users. By applying this code, you can enhance the visual impact of your website or add an interesting effect to images in various creative projects.
How to Create Image Glitch Effect using JavaScript
1. First, load Reset CSS by adding the following CDN link into the head tag of your webpage.
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
2. Create a div element with the class name “glitch”, and place the image in CSS as the background of this div element.
<main> <div class="glitch"> </div> </main>
3. Use the following CSS styles for the glitch animation. Simply replace the “background-image” property with the URL of your preferred image.
main{
  position: relative;
  min-height: 720px;
}
.glitch {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: url("https://codepel.com/img/joshua-rondeau.jpg");
  background-size: 100%;
  background-repeat: no-repeat;
  background-position: center center;
  background-attachment: fixed;
  background-color: #b5bac2;
  overflow: hidden;
}
.glitch__box {
  position: absolute;
  background-image: url("https://codepel.com/img/joshua-rondeau.jpg");
  background-size: 100%;
  background-repeat: no-repeat;
  background-position: center center;
  background-attachment: fixed;
  background-color: #b5bac2;
}
4. Finally, add the following JavaScript function to your project to activate the image glitch effect.
const backgroundImage = document.querySelector('.glitch'),
      glitch = document.getElementsByClassName('glitch__box');
      count = 20;
  
for (let i = 0; i < count; i++) {
  let glitchBox = document.createElement('div');
  glitchBox.classList.add('glitch__box');
  backgroundImage.appendChild(glitchBox);
}
setInterval(function(){
  for (let j = 0; j < glitch.length; j++) {
    glitch[j].style.left = Math.floor(Math.random()*100) + 'vw';
    glitch[j].style.top = Math.floor(Math.random()*100) + 'vh';
    glitch[j].style.width = Math.floor(Math.random()*400) + 'px';
    glitch[j].style.height = Math.floor(Math.random()*100) + 'px';
    glitch[j].style.backgroundPosition = Math.floor(Math.random()*10) + 'px';
  }
}, 200);
That’s all! hopefully, you have successfully created an image glitch effect. If you have any questions or suggestions, feel free to comment below.
				
	
 