I have a link leading to 1 of 6 articles displaying on my website. Every 6 seconds, the text link switches to the next. I'd like for the order to be randomized, though, so that each article has the same likelihood to be chosen. Can anyone help?

My code on gist is here:
https://gist.github.com/jonsan32/5982135

The raw code is here:
https://gist.github.com/jonsan32/5982135/raw/4952a61f968cfa372bdebe9a81d97c75456526a4/gistfile1.txt

Thank you in advance.

Dani AI

Generated

A simple, robust approach is to build a randomized play order once and walk it, then reshuffle when the list finishes. That avoids predictable sequences and is easy to paste into an existing rotator. was right to point toward Math.random; the difference is whether random draws are done independently each tick (can repeat) or used to shuffle a full order (no repeats within a cycle). Because mentioned limited coding experience, the example below uses plain DOM calls and minimal logic for easy adaptation.

// Fisher-Yates shuffle
function shuffle(arr) {
  for (let i = arr.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [arr[i], arr[j]] = [arr[j], arr[i]];
  }
}

const items = Array.from(document.querySelectorAll('.rotator a')).map(a => ({ text: a.textContent, href: a.href }));
shuffle(items);

let idx = 0;
let last = null;

function showNext() {
  const item = items[idx++];
  const linkEl = document.querySelector('.rotator .link'); // change selector to match page
  linkEl.textContent = item.text;
  linkEl.href = item.href;
  last = item;
  if (idx >= items.length) {
    shuffle(items);
    // avoid immediate repeat across cycles
    if (items[0].href === last.href && items.length > 1) [items[0], items[1]] = [items[1], items[0]];
    idx = 0;
  }
}

showNext();
const timer = setInterval(showNext, 6000);

Notes and troubleshooting: swapping the first two items after a reshuffle prevents the same link showing twice in a row. If equal long‑term probability (with possible immediate repeats) is acceptable, a single-line random pick each tick (Math.floor(Math.random()*n)) also works. Adapt the selectors to the actual HTML, test in the console with console.log(items) to verify random order, and clear the interval when the rotator is removed or on page unload to avoid leaks.

Recommended Answers

All 2 Replies

Instead of index++ use the Math.random() function. But you should try to avoid the same number being chosen again.

Sounds simple enough, but I have no clue what you're talking about. I should've mentioned that I suck at coding. I'm just good at googling stuff to copy and paste. What should I search for to find a tutorial? Would it be hard to actually implement?

Thank you for the response either way. I truly appreciate it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.