Skip to content

Instantly share code, notes, and snippets.

@leoafarias
Created April 3, 2019 17:57
Show Gist options
  • Save leoafarias/e437880d7703d414006ab87e95a4ec1a to your computer and use it in GitHub Desktop.
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
// 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
}
@psmithson
Copy link

Little typo. Change
// Just add class "particle-js" to the elements you would...
to
// Just add class "particles-js" to the elements you would...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment