Implementing a dynamic display of images using JavaScript: a step-by-step guide

I have a set of 4 light bulbs:

<div id="bulb1" class="lightbulb"><img src=".\images\bulb.png" /></div>
<div id="bulb2" class="lightbulb"><img src=".\images\bulb.png" /></div>
<div id="bulb3" class="lightbulb"><img src=".\images\bulb.png" /></div>
<div id="bulb4" class="lightbulb"><img src=".\images\bulb.png" /></div>

My task is quite unique - I need to accomplish it using JavaScript.

I have an array with 4 elements {1, 2, 3, 4}. Initially, all bulb images are hidden.

The goal is to randomly illuminate one bulb from the array. For example, if 2 is selected, then the second bulb will light up.

Then after 500 milliseconds, another random selection is made - say 4 this time, illuminating the fourth bulb while hiding the second one.

This process should repeat four times, ensuring that each time a different bulb lights up. What would be the best approach and structure for achieving this?

All bulbs are initially turned off by calling this function:

function hideBulbImages()
    {
        document.getElementById('bulb1').style.visibility = "hidden";
        document.getElementById('bulb2').style.visibility = "hidden";
        document.getElementById('bulb3').style.visibility = "hidden";
        document.getElementById('bulb4').style.visibility = "hidden";
    }

I am considering implementing the showBulbImage function...

I have created a function to sequentially illuminate the bulbs every second like so:

function showBulbImages()
    { 
        var blink_count = 0;
        var blink_the_bulbs = setInterval(function() {
            blink_count+=1;
            hideBulbImages();
            var blinking_bulb = "bulb" + blink_count;
            document.getElementById(blinking_bulb).style.visibility = "visible";
            if (blink_count > 4) 
            {
                 clearInterval(blink_the_bulbs);
            }

        }, 1000);
    }

Now, the challenge lies in randomizing the visibility of the bulbs.

Answer №1

To display random images, utilize the setInterval() and Math.random() functions.

The function get_random_bulb() generates a random number, hides the currently visible image, and then displays a randomly selected image.

Here is the JavaScript code:

$(document).ready(function () {
get_random_bulb();
function get_random_bulb() {
    var a = (parseInt(Math.random() * 4));
    $(".lightbulb img.block").removeClass("block").addClass("none");
    $(".lightbulb:eq(" + a + ") img").removeClass("none").addClass("block");
}
setInterval(function () {
    get_random_bulb();
}, 500);

HTML code for the lightbulbs:

<div id="bulb1" class="lightbulb">
    <img src=".\images\bulb.png" class="none" />
</div>
<div id="bulb2" class="lightbulb">
    <img src=".\images\bulb.png" class="none" />
</div>
<div id="bulb3" class="lightbulb">
    <img src=".\images\bulb.png" class="none" />
</div>
<div id="bulb4" class="lightbulb">
    <img src=".\images\bulb.png" class="none" />
</div>

View the live example on JSFiddle.

Answer №2

Thanks to Hiral’s guidance and some additional research, I successfully integrated the desired functionality into my project. Below is the completed showBulbImage function that I ended up with:

function showBulbImages()
    { 
        var blink_count = 0;
        var myArray = ['1', '2', '3', '4'];
        var randomArray = shuffleArray(myArray)
        var blink_the_bulbs = setInterval(function() {      
            var blinking_bulb = "bulb" + randomArray[blink_count];
            document.getElementById(blinking_bulb).style.visibility = "visible";
            blink_count+=1;
            if (blink_count > 3) 
            {
                 clearInterval(blink_the_bulbs);
            }
        }, 1000);
    }

    function shuffleArray(array) 
    {
        for (var i = array.length - 1; i > 0; i--) 
        {
            var j = Math.floor(Math.random() * (i + 1));
            var temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
        return array;
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Seeking guidance on creating an uncomplicated CSS tooltip

Can anyone help me troubleshoot why my CSS tooltip isn't working correctly? I've been trying to create a simple method for tooltips, but they are displaying inconsistently across different browsers. In Firefox, the tooltips appear in random locat ...

Tips for ensuring the border matches the size of the image

I am in the process of creating a website that includes a filter option. My plan is to have the filters displayed on the left side and the items on the right side. To achieve this layout, I have implemented a scrollable div for the items. However, I notic ...

Comparison of Foundation5 source ordering: main content versus sidebar

I recently set up a layout with three columns using ZURB Foundation 5. The two sidebars are on the left and right, while the main content area is in the middle. While trying to follow the source ordering instructions in the documentation, I encountered so ...

Secure your password with Vue JS encryption techniques

I am looking for a way to safely encrypt passwords on my Vue JS web application. While I already have a hash encrypter set up on the API, I am running into an issue where the password is displayed as plain text during the signin or signup call. Any recom ...

Fetching and storing external data into an array using AngularJS

I'm attempting to retrieve data from a database using an external script in order to populate a select dropdown. However, my current approach results in numerous empty li elements being generated. Although the count seems correct, nothing is actually ...

Handling the width and borders of CSS cells that are positioned outside of a table

Welcome! I recently created a simple gantt organizer as part of a demo. My goal was to make the main table scrollable while keeping certain columns "frozen" for easy visibility when navigating through the data. To achieve this, I followed some advice found ...

Error: start-up unsuccessful for parse-server

After following the instructions at the link provided (https://github.com/parse-community/parse-server), I attempted to install Parse Server locally by running the commands below: $ npm install -g parse-server mongodb-runner $ mongodb-runner start $ parse ...

Retrieve the erased document using Google's cache feature

After accidentally overwriting my .php web document file with an old version, I attempted to access the cached copy on Google. The only thing I could find was the HTML scripts, as the PHP coding was not visible. Now I am seeking a method to recover the e ...

Launching an external JavaScript from within a separate JavaScript file

I'm in the process of developing a virtual 'directory' for various locations in my city to assist fellow students. Here's the concept: On a map, I've pinned all the locations Clicking on these pins triggers a JavaScript funct ...

What is the process for transforming a string into a dictionary using jinja2?

I have a variable called {{data}} which contains a string formatted like this: *{"a": "1", "b": "2", "c": 3, "d": 4}* My goal is to access the values in this format: *{{data.a}} --> 1 {{data.b ...

Are there any PHP functions available that can check if the query string is empty?

I have experience with server-side development but not much in PHP. Currently, I'm working on a semi-basic tool with 10-15 pages and using the $_GET parameter for navigation. Is there a PHP function that can check if the query string is empty to dete ...

Issue with the Z-Index property not functioning as expected on unordered lists within a dropdown menu

I have a dropdown menu that opens to the left, but it is displaying underneath the content. I attempted adjusting the z-index of the content to 1 and the dropdown to 2, however, this did not resolve the issue. Here is a sample in jsFiddle: https://jsfiddl ...

Tips for resizing an object in a single direction using THREE.JS

I have encountered an issue while adding a cube to my scene using THREE.JS. When I try to change the height of the cube by increasing its y coordinate, it also seems to expand in the negative y direction as well. var cubeGeometry2 = new THREE.BoxGeomet ...

What is the process for activating the quasar timepicker once a user has selected a time?

The functionality of the timepicker in Quasar doesn't quite meet my expectations. I don't want to add another library just for this feature. The main issue I have is that it doesn't close automatically after selecting a time. I managed to fi ...

Maintain parent hover effect while child is being hovered over

After exploring various solutions to fix an issue, I've hit a roadblock. Adding CSS and jQuery code seemed promising at first, but upon refreshing the browser, a new problem emerged. The parent element retained its hover state background color, but th ...

Having issues with Angular chart.js onClick event? Learn how to retrieve all elements of a bar when it is clicked on

As a newcomer to Chart.js, I am exploring how to implement click events for when a chart is generated. My current challenge involves accessing all the elements of a bar upon clicking it. Unfortunately, the onClick method is not functioning as expected at ...

Rendering sibling components on Multiple Select Material UI in React

Here is my current challenge: I am trying to implement a multiple select feature with checkboxes in React using Material UI. The desired outcome should resemble the image linked below: https://i.stack.imgur.com/TJl8L.png I have structured my data in an a ...

When you hover, there is no writing cursor in sight

I'm looking for a way to display a label on an input field and have a writing cursor show up when hovering over the label. I am not interested in using a placeholder label. Do you have any simple solutions for this? See the code snippet below: JSFiddl ...

Selenium WebdriverIO is unable to detect all the texts within the options of a ReactJS list

Greetings! I encountered an issue while trying to retrieve text from an element using a ReactJS drop-down list. The WebDriver version is 3.6.0 and Chromium version is 63. Below is a snippet of the DOM: <div class="Select-menu-outer" data-reactid=".0. ...

Ways to determine if a Less file matches the compiled CSS file

Recently, I inherited a website that utilizes LESS for CSS pre-processing. My task involves updating certain styles; however, I am uncertain whether the former developers made changes to the LESS files and then compiled the CSS, or if they simply edited th ...