JavaScript function to randomly rotate multiple div sections on a webpage

I created a JavaScript function that opens a popup displaying some text. However, I’m facing an issue with rotating two ‘section’ elements. When I add another section with the class ‘special’, only the first one appears on the page. I need assistance to include 1 or 2 additional elements for rotation. The goal is to have multiple sections with the class ‘special’ displayed in random order, and once the final one is shown, the rotation should stop. Any help would be greatly appreciated.

setInterval(function () {
    $('.special').stop().fadeToggle('slow');
}, 2000);
$('.special-close').on('click', function () {
    $('.special-notification').stop().fadeToggle('slow');
});
<section class="special">
    <div class="special-notification">
        <div class="special-content">
            <div class="special-image">
                <img src="new-image.png" alt="notification">
            </div>
            <div class="special-text">
                <p>This is a notification message.</p>
            </div>
        </div>
        <button class="special-close">Close</button>
    </div>
</section>

To rotate multiple 'section' elements with class 'special' randomly, consider using JavaScript's Math.random() instead of jQuery animations.

const elements = document.querySelectorAll('.special');
let currentIndex = 0;

function showNextElement() {
    elements[currentIndex].style.display = 'none';  // Hide current
    currentIndex = Math.floor(Math.random() * elements.length);  // Random index
    elements[currentIndex].style.display = 'block';  // Show next
    setTimeout(showNextElement, 2000);  // Repeat
}

showNextElement();

This will rotate the sections until you stop it. Also, make sure each section starts with style="display:none" in your HTML, except the one you want to show first.

Rotating multiple 'section' elements in a random order can be done effectively by utilizing JavaScript for more control over the display logic. While the existing solution provided by Alex_Brave is a good starting point, you might want to ensure that each section is shown once in a random order and then stop the rotation.

Here’s an enhanced example to achieve that:

const elements = Array.from(document.querySelectorAll('.special'));
const indices = elements.map((_, index) => index); // Create an array of indices
let shuffledIndices = shuffle(indices);
let currentIndex = 0;

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

function showNextElement() {
    elements.forEach(element => {
        element.style.display = 'none'; // Hide all elements
    });

    if (currentIndex < shuffledIndices.length) {
        elements[shuffledIndices[currentIndex]].style.display = 'block'; // Show next random element
        currentIndex++;
        setTimeout(showNextElement, 2000); // Move to next element after delay
    }
}

showNextElement();

This code snippet leverages a shuffle function to shuffle indices of the sections, ensuring each section is displayed once in a random sequence. After all sections have been shown, the function will stop.

To use this, ensure all your sections have the class special and initially set their style to display: none; in your HTML, except the one you wish to display first.

To achieve a random rotation of multiple 'section' elements with the class 'special', displaying each one once and then stopping, you can enhance your JavaScript code using a shuffling technique for efficiency and clarity.

Here's a practical approach:

const elements = Array.from(document.querySelectorAll('.special'));
const indices = elements.map((_, index) => index);
let shuffledIndices = shuffle(indices);
let currentIndex = 0;

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

function showNextElement() {
    elements.forEach(element => {
        element.style.display = 'none'; // Hide all elements
    });

    if (currentIndex < shuffledIndices.length) {
        elements[shuffledIndices[currentIndex]].style.display = 'block'; // Show next random element
        currentIndex++;
        setTimeout(showNextElement, 2000); // Move to next element after a delay
    }
}

showNextElement();

This script includes a shuffling method that ensures each section is displayed once in a random order before the rotation stops. To make this work seamlessly, initialize your HTML sections with style="display: none;" to keep them hidden, except for the one you prefer to start showing first. This method optimizes the display logic and provides a straightforward solution.

To randomly rotate multiple 'section' elements with the class 'special', you can modify your JavaScript code as shown below. This approach ensures each section is displayed once in a random order before the rotation stops.

const elements = Array.from(document.querySelectorAll('.special'));
const indices = elements.map((_, index) => index); // Create an array of indices
let shuffledIndices = shuffle(indices);
let currentIndex = 0;

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

function showNextElement() {
    elements.forEach(element => {
        element.style.display = 'none'; // Hide all elements
    });

    if (currentIndex < shuffledIndices.length) {
        elements[shuffledIndices[currentIndex]].style.display = 'block'; // Show next random element
        currentIndex++;
        setTimeout(showNextElement, 2000); // Move to next element after delay
    }
}

showNextElement();

Ensure all your sections have the class special and initially set their style to display: none; except for the one you want to show first in your HTML. This code snippet leverages a shuffle function to randomize indices, ensuring each section is shown once and stops automatically.

To enhance your task of rotating multiple section elements with the class 'special', we can employ a refined approach that assures each section is shown once before stopping completely. Building on the shuffling technique, we can integrate a more comprehensive method with added flexibility for transitions.

Consider using the following JavaScript approach:

const elements = [...document.querySelectorAll('.special')];
let currentIndex = 0;

// Create a shuffled array of element indices
const indices = elements.map((_, idx) => idx);
const shuffledIndices = indices.sort(() => Math.random() - 0.5);

function showNextElement() {
    // Hide all sections
    elements.forEach(el => el.style.display = 'none');

    // Show next section
    if (currentIndex < shuffledIndices.length) {
        elements[shuffledIndices[currentIndex]].style.display = 'block';
        currentIndex++;
        setTimeout(showNextElement, 2000); // Transition delay
    }
}

showNextElement();

Key Points to Ensure Functionality:

  • CSS Initial State: Each section should have style="display: none;" to start off hidden, except possibly the first you wish to display.
  • Shuffling the Indices: We randomize the array of indices to ensure each 'special' section appears in a different random order.

This solution provides a clean and easy-to-maintain approach by separating the shuffle logic from the display logic, making it flexible enough for any number of sections. Implementing these adjustments will achieve the desired rotation effect effectively.