VanillaJS Bubble SVG + hover
by Jens Kühn
HTML
<svg id="bubbles-footer" class="c-bubbles" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1920 1920"></svg>
CSS
body{
background-color: #f6f5de
}
#bubbles-footer {
display: block;
height: 100px;
width: 100%;
}
.c-bubbles circle {
fill: #f6f5de;
stroke: #100;
stroke-miterlimit: 10;
stroke-width: 3px;
}
JavaScript
function setViewBox() {
bubblesFooter.setAttributeNS(null, "viewBox", "0 0 " + screenWidth + " 100");
}
function buildCircles() {
for (i = 0; i < totalCircles; i++) {
createFooterCircles();
}
}
function createFooterCircles() {
var num = getRandom(4, 26);
var elemSVG = document.createElementNS(svgNS, "circle");
positionFooterCircle(elemSVG);
elemSVG.setAttributeNS(null, "r", num);
bubblesFooter.appendChild(elemSVG);
}
function bubbleHover() {
var arrBubbles = document.querySelectorAll("circle");
for (i = 0; i < arrBubbles.length; i++) {
arrBubbles[i].addEventListener("mouseover", function() {
fillColor(this);
});
}
}
function fillColor(elemBubble) {
elemBubble.setAttribute("style", "fill:" + colors[Math.floor(Math.random() * colors.length)]);
}
function getRandom(start, end) {
return start + Math.floor(Math.random() * (end - start + 1));
}
function rearrangeCircles() {
var arrBubbles = bubblesFooter.querySelectorAll("circle");
for (i = 0; i < arrBubbles.length; i++) {
positionFooterCircle(arrBubbles[i]);
}
}
function positionFooterCircle(elemBubble) {
var cx = getRandom(1, screenWidth);
var cy = getRandom(28, 300);
elemBubble.setAttributeNS(null, "cx", cx);
elemBubble.setAttributeNS(null, "cy", cy);
}
var colors = ["#66ccff", "#110000", "#c16100", "#be6700", "#be6700", "#cdcaa2", "#0d004c", "#ffffff", "#b1a89e"];
var bubblesFooter = document.getElementById("bubbles-footer");
var screenWidth = window.innerWidth;
var screenHeight = window.innerHeight;
totalCircles = 1500;
initialColoredCircles = 1e3;
svgNS = "http://www.w3.org/2000/svg";
setViewBox();
buildCircles();
var paths = document.querySelectorAll("circle");
bubbleHover();
window.addEventListener("resize", function() {
screenWidth = window.innerWidth;
screenHeight = window.innerHeight;
setViewBox();
rearrangeCircles();
bubbleHover();
});