Created
April 3, 2019 17:57
-
-
Save leoafarias/e437880d7703d414006ab87e95a4ec1a to your computer and use it in GitHub Desktop.
A snippet of code to use multiple instances of particle.js within the same page
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Just add class "particle-js" to the elements you would like to load particles.js on. No need to pass each individual ID | |
window.onload = startParticles; | |
window.onresize = startParticles; | |
function startParticles() { | |
var particleEls = document.getElementsByClassName("particles-js"); | |
if (particleEls) { | |
Object.keys(particleEls).forEach(function(key) { | |
loadParticles(particleEls[key]); | |
}); | |
} | |
} | |
function loadParticles(el) { | |
if(el.id === ""){ | |
el.id = randomId(); | |
} | |
particlesJS(el.id, PARAMS_JSON); | |
} | |
// Generates a random id | |
function randomId(){ | |
let string_length = 10; | |
let random_string = ''; | |
let random_ascii; | |
for(let i = 0; i < string_length; i++) { | |
random_ascii = Math.floor((Math.random() * 25) + 97); | |
random_string += String.fromCharCode(random_ascii) | |
} | |
return random_string | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Little typo. Change
// Just add class "particle-js" to the elements you would...
to
// Just add class "particles-js" to the elements you would...