Animated Background
CSS/JS animated background that interacts on cursor movement
by Glynne Turner
HTML
<div class="banner">
<img id="bg"
src="https://source.unsplash.com/LAaSoL0LrYs/1920x1080"
/>
<div class="foreground">
<h1>HERO HEADER HERE</h1>
<p>Lorem Ipsum Dolar Sit Amet</p>
<button>READ MORE</button>
</div>
</div>
CSS
* {
-webkit-box-sizing: border-box;
box-sizing: border-box;
padding:0;
margin:0;
}
body {
margin: 0;
padding: 0;
overflow-x: hidden;
}
#bg {
position: relative;background-size: contain;
height: 100vh;
min-width:100vw;
max-width:100vw;
transition: all 0.1s ease 0s;
-webkit-transform: scale(2) translate3d(0px,0px,0px);
-moz-transform: scale(2) translate3d(0px,0px,0px);;
transform: scale(2) translate3d(0px,0px,0px);;
}
h1 {
color: white;
text-align: center;
font-family: sans-serif;
font-size: 5vw;
font-weight: 900;
margin: 12vw 0px 15px 0px;
padding: 0px;
pointer-events: none;
-webkit-text-shadow: 1px 1px 1px black;
text-shadow: 1px 1px 1px black;
}
p {
color: white;
text-align: center;
font-size: 3vw;
padding: 0;
font-family: sans-serif;
margin: 0px;
pointer-events: none;
}
button {
display: block;
width: 150px;
margin-left: auto;
margin-right: auto;
margin-top: 20px;
text-align: center;
background-color: rgba(0, 0, 0, 0.3);
color: white;
padding: 10px 20px;
cursor: pointer;
border: none;
}
button:focus {
outline: none;
}
button:hover {
background-color: rgba(0, 0, 0, 0.9);
}
.banner {
position: relative;
top: 0;
left: 0;
width: 100%;
height: auto;
overflow: hidden;
border: 0px solid black;
}
.foreground {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.2);
}
JavaScript
window.addEventListener('load', function() {
document.querySelector('.foreground').addEventListener(
'mousemove',
function(event) {
if (window.event) {
event = window.event; // IE Fix
}
var mousex = event.clientX;
var mousey = event.clientY;
var tar = document.getElementById('bg');
//tar.style.webkitTransform = 'scale(2)';
tar.style.webkitTransform =
'scale(2) translate3d('+ -mousex/8+'px,'+ -mousey/8+'px,'+0+'px)';
}, false);
document.querySelector('.foreground').addEventListener(
'mouseout',
function() {
var tar = document.getElementById('bg');
//tar.style.webkitTransform = 'scale(2)';
tar.style.webkitTransform =
'scale(2) translate3d('+0+'px,'+0+'px,'+0+'px)';
}, false);
});