Can different scripts be used to call a single script?

I'm trying to display random images in four divs using code I found on SO:

<script type="text/javascript>
        function get_image(div_id){
            var imgCount = 3;
            var dir = 'images/';
            var randomCount = Math.round(Math.random() * (imgCount - 1)) + 1;
            var images = new Array
                images[1] = "1.jpg",
                images[2] = "2.jpg",
                images[3] = "3.jpg",
            document.getElementById(div_id).style.backgroundImage = "url(" + dir + images[randomCount] + ")";
            console.log("div_id = " + div_id)
        }
    </script>

The divs are supposed to call the function like this:

<div class="image_holder" id="left_top">
                <script id="lt_innerscript">
                    var div_id = document.getElementById("lt_innerscript").parentElement.id;
                    var myVar = setInterval(function() { get_image(div_id); }, 800);
                </script>   
            </div>

However, only the last div is displaying an image while the others remain blank. What could be causing this issue?

CSS styles have been applied to two separate divs with ids "left" and "right."

#left{
    float: left;
    background: blue;
    width: 300px;
    height: 100%;
    color: #005CB9;
}

and

.image_holder {
    position: relative;
    width: 300px;
    height: 256px;
}

Answer №1

In my particular scenario, I came up with a solution that worked perfectly...

Here's the modified code snippet from Stack Overflow tailored to fit my requirements (images labeled as 1.jpg, 2.jpg, etc):

function show_images(the_div){
    console.log(the_div)
    var imgCount = 19;
    var dir = 'images/';
    var imagenum = Math.round(Math.random() * (imgCount - 1)) + 1;
    var theimage = imagenum.toString() + ".jpg"
    document.getElementById(the_div.id).style.backgroundImage = "url(" + dir + theimage + ")";

}

Instead of having individual scripts within each div element to invoke it, I implemented the following function that retrieves divs from both side panels:

function get_divs(){
    var left = document.getElementById("left");
    var right = document.getElementById("right");

    var l_divs = left.getElementsByTagName("div");
    var r_divs = right.getElementsByTagName("div");

    return [l_divs, r_divs]
}

This method is then utilized by the subsequent code block, which randomly selects three numbers between 1 and 6 in a loop. Numbers below 3 are assigned to the left side, while those above 4 correspond to the right side. However, if the number exceeds 4, it subtracts 3 since there are only 3 divs per side.

The respective div image is then set using the previously defined show_images() function.

function update_divs(){
    divs = get_divs()
    l_divs = divs[0]
    r_divs = divs[1]

    for(var i=0; i<4; i++){
        rnd = Math.floor((Math.random() * 6));
        if (rnd <= 2){
            show_images(l_divs[rnd])
        }else{
            rnd -= 3;
            show_images(r_divs[rnd])
    }
}

}

Lastly, I included the following script at the end of the page to ensure the divs are updated periodically:

<script>    
    setInterval(update_divs, 1600)
</script>

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

Display or conceal a div element using a dropdown menu selection

I have implemented the following code, which is currently functional and was sourced from a different thread on Stack Overflow: <Select id="colorselector"> <option value="red">Red</option> <option value="yellow">Y ...

Closing the nested accordion will collapse all sections within the accordion

I'm currently facing an issue with my nested accordions. I've been attempting to nest them in a way that doesn't require writing additional jQuery code for each new one added. As an example, I've created a jsfiddle... https://jsfiddle. ...

Adjust the class based on the model's value in AngularJS

items = {'apple', 'banana', 'lemon', 'cat', 'dog', 'monkey', 'tom', 'john', 'baby'} html <div class="variable" ng-repeat="item in items">{{item}} </div> ...

invoke a function through a form in Angular

I am encountering an issue with invoking a function from Angular. This particular function has a dual purpose - it uploads an image to S3 and saves the form data along with the URL of the image in the MongoDB database. Below is the HTML snippet where I cal ...

Switching an image when hovering over another div - a simple tutorial

Currently, I am in the process of creating a product page for metal address numbers on a website. These numbers are available in four distinct colors: gold, chrome, black, and brown. My goal is to enable users to hover over a specific color div, prompting ...

What is the best way to dynamically call a different PHP file each day for an entire year?

As a PHP novice, my goal is to integrate a daily meditation feature that corresponds to the current day. For example, on January 1st, I would like to display content from 1_1.php, and on the following days, it should load 1_2.php, 1_3.php, continuing unti ...

Unraveling the Distinctions: Identifying an Admin vs. a User within the API

When working with the express framework, I encounter a situation where I need to restrict access to certain API endpoints. For example, I have this line in the API: router.delete('/user',(req, res) => { //deleting...} Now, I want only an Adm ...

What is the best way to implement validation in React where selecting an option from one dropdown menu automatically disables that same option in another dropdown menu?

In my React form design, I am working with two dropdown categories: "What Include" and "What is not include". My goal is to disable any option selected in the "What Include" menu from being available in the "What not Include" dropdown. Below is the code f ...

What is the best way to toggle between two forms with JavaScript?

I have designed a login screen with two forms inside one div. The first form contains the login box, while the second form is for registration and is hidden using CSS with display:none;. Below the login button, there is a paragraph with an anchor tag to cl ...

SVG - Various images displaying unique characteristics

Trying to create a visual graphic with two images, one representing an empty state and the other a filled state. The challenge is determining how to adjust the width of only one image while keeping them the same height using a clip path. For example, I w ...

Comparison Between Angular and Web API in Regards to Racing Condition with Databases

Currently, I am working on an Angular service that iterates through a list and makes web API calls to add or modify records in the database. The service operates on a small record set with a maximum of 10 records to update. After the loop completes, Angula ...

Is it possible to apply SlideToggle() to Div elements that have their Display property set to Table-Cell?

I am facing an issue on my web page where I have a series of div elements styled with display: table and their child div elements styled with display: table-cell. I am looking to use slideToggle() on a specific cell to change its content. However, I have c ...

Guide on how to make the parent scrollable once children are dynamically added

Do you know why the .wrap-max-height is not working properly? I am expecting it to be limited by 100vh - 108px and for .ins to be scrollable if needed. Any assistance would be greatly appreciated! $('button').on('click', function() ...

Place the image at right:0px position, but it won't display

I am trying to position an image at the end of a sentence within a div element. No matter what I try, the image always appears next to the end of my text. Here is the code I am using: <div id='xi' class='xc'>Text comes here and ...

Animation Effects in Opera and Internet Explorer

Just unveiled my latest project, CSSload.net - an awesome tool for generating CSS spinners and bars. The animations are running smoothly on Firefox and Webkit browsers. Curious if anyone has tips on animating elements like this in Opera and IE? ...

Guide to customizing the appearance of a Bootstrap Component within an Angular project

Is it possible to completely customize the style/CSS of a component from ng-bootstrap? Here's the issue I'm facing: I have this code... <ngb-datepicker #dp [(ngModel)]="model" (navigate)="date = $event.next" style ...

Is there a way to sort a table using a dropdown menu selection as a filter?

I am currently working on a project that involves a table with three columns, which are typically populated from a SQL database. My goal is to filter the third column based on the value selected from a dropdown menu. I came across a helpful tutorial on W3 ...

Customize the progress bar color in Bootstrap by setting a unique color to it

Is it possible to apply a custom color to the progress bar in Bootstrap that is not one of the standard options like success, info, warning or danger? I attempted adding the following code snippet to my bootstrap-theme.css file: .progress-bar-custom { b ...

How can we avoid nesting multiple functions as callbacks in Node.js/Express applications to ensure sequential execution?

Currently, I am in the process of creating a straightforward URL shortening web application. My main objective behind this endeavor is to gain a better understanding of JavaScript, with a specific focus on Node (especially Express), and Mongo. In this web ...

Traverse Through Every Column of an HTML Table and Retrieve the Information with jQuery

Trying to extract data from within the <tbody> tags in an HTML table. The structure of each row is as follows: <tbody> <tr> <td>63</td> &l ...