Carousel Javascript Randomization | XM Community
Skip to main content

Hello, 

I have a list of 10 items that I want to randomize by splitting them into two sets: the first set is shuffled randomly, and the second set is reordered to align with the shuffled order of the first. For example, an accepted shuffle of A1, B1, C1, D1, E1, A2, B2, C2, D2, E2 would be B1, E1, C1, A1, D1, B2, E2, C2, A2, D2. 

 

I was able to do this for a side-by-side question, however my logic doesn’t seem to work for a matrix type question that is displayed as carousel. My JS code is overwritten and the cards are shown in the non-shuffled order. I would appreciate any pointers. Please find my code below. Thank you!

 

Qualtrics.SurveyEngine.addOnReady(function () {
    //get container
    var questionContainer = this.getQuestionContainer();

    if (!questionContainer) {
        console.error('container not found');
        return;
    }


    //get cards
    var cards = questionContainer.querySelectorAll('.CarouselCard'); 
    
    if (cards.length === 0) {
        console.error('no cards');
        return;
    }


    //shuffle
    var firstSet = Array.from(cards).slice(0, 5);
    var secondSet = Array.from(cards).slice(5, 10);

    var shuffledFirstSet = firstSet.slice();
    
    for (let i = shuffledFirstSet.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        shuffledFirstSetli], shuffledFirstSet(j]] = )shuffledFirstSetj], shuffledFirstSetii]];
    }

    //add second set 
   var finalOrder = shuffledFirstSet.concat(
        shuffledFirstSet.map(card => secondSetdfirstSet.indexOf(card)]));
    
    
    //append to carousel
    var carouselContainer = questionContainer.querySelector('.CarouselCardContainer');
    
    if (!carouselContainer) {
        console.error('container not found 2');
        return;
    }

    finalOrder.forEach(card => carouselContainer.appendChild(card));

    console.log('shuffled!');
});

 

Be the first to reply!

Leave a Reply