cmbaginski
cmbaginski

Reputation: 3

How to add different data attribute to random elements in an array in Javascript?

I'm working with Animate on Scroll and want to assign a different animation delay to random elements in an array (or even vs. odd), which are displayed as list items. Since you have to add/change the data attribute (e.g. data-aos-delay="50"), I'm not sure how best to do this so that half the list items have a different delay time. Thanks so much!

AOS on GitHub

var words = ["Superheroes", "supervillains", "aliens", "monsters", "wizards", "warriors", "witches", "barbarians", "creatures", "robots", "cyborgs", "droids", "time travelers", "spaceships", "star fighters "]

function wordsLoad() {
// Shuffle function from http://stackoverflow.com/a/2450976
function shuffle(array) {
    var currentIndex = array.length, temporaryValue, randomIndex;

    while (currentIndex !== 0) {
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }
    return array;
}
words = shuffle(words);

//create HTML for each word
function createWord(word) {
    return '<li class="text-uppercase" data-aos="slide-up">' + word + '</li>';
}
//add words HTML to page
function generateWords() {
    const group = document.querySelector('.products');//.products of class of <ul>
    const wordHTML = words.map(function(word) {
        return createWord(word);
    });
    group.innerHTML = wordHTML.join('');
}
generateWords();
}
$(document).ready(function() {
wordsLoad();
});

Upvotes: 0

Views: 465

Answers (1)

Ethan Kelley
Ethan Kelley

Reputation: 113

If you're asking about adding data dynamically to the html strings you are generating, template literals can help. Assuming you just want to alternate between two different delay values, you could try this:

function createWord(word, delay) {
    // using a template literal will enable string interpolation.
    // note the use of backticks (instead of single quotes):
    return `<li class="text-uppercase" data-aos-delay="${delay}" data-aos="slide-up">${word}</li>`;
}

function generateWords() {
    const group = document.querySelector('.products');

    const delayValues = [50, 100];
    const wordHTML = words.map(function(word, idx) {
        const delay = delayValues[idx % 2]; // alternate delay values for even vs odd words
        return createWord(word, delay);
    });
    group.innerHTML = wordHTML.join('');
}

Upvotes: 1

Related Questions