What methods can I implement to showcase random images in JavaScript using a JSON array value?

I am currently working on a fun avatar generator project. The challenge I'm facing is that each hairstyle consists of two parts (front and back), and when loaded randomly, the colors don't always match. To tackle this issue, I have organized the assets in a JSON file where they are grouped by colors. For instance, every ginger front hair, back hair, and eyebrows will always load together.
The tricky part now is figuring out how to implement these values in the random loading process, which has proved to be quite challenging for me as someone new to using JSON.

If anyone has any advice or leads on how to solve this problem, it would be greatly appreciated :-)

Below is a snippet of my JS script:

document.addEventListener("DOMContentLoaded", function() {
    // Code block
});

And here is an excerpt from my JSON file showing examples of hairstyles with corresponding colors:

    {
        "img": "/img/backhair/man/backhair1.png",
        "color": "blond"
    },

    {
        "img": "/img/backhair/man/backhair2.png",
        "color": "ginger"
    },

    {
        "img": "/img/backhair/man/backhair3.png",
        "color": "auburn"
    },

    {
        "img": "/img/backhair/man/backhair4.png",
        "color": "chestnut"
    },

    {
        "img": "/img/backhair/man/backhair5.png",
        "color": "black"
    },

Answer №1

Here's a simple method you can use:


    let backhair = get_random_image(20, 1); // making sure it matches
    let body = get_random_image(25, 1);
    let clothes = get_random_image(12, 1);
    let eyebrows = get_random_image(20, 1); // ensuring match
    let eyes = get_random_image(30, 1);
    let mouth = get_random_image(5, 1);
    let nose = get_random_image(4, 1);
    let fronthair = get_random_image(20, 1); // confirming match   

To simplify this process, randomize once and assign the same value to others:


    let matched = get_random_image(20, 1); // make sure it matches
    let backhair_nbr = matched;
    let body_nbr = get_random_image(25, 1);
    let clothes_nbr = get_random_image(12, 1);
    let eyebrows_nbr = matched;
    let eyes_nbr = get_random_image(30, 1);
    let mouth_nbr = get_random_image(5, 1);
    let nose_nbr = get_random_image(4, 1);
    let fronthair_nbr = matched;  

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

Having trouble with querySelector or getElementById not functioning properly?

Currently, I am in the midst of developing an experimental web application that features a quiz component. For this project, I have implemented a Python file to handle the questions and quiz functionalities. However, I have encountered an issue with the Ja ...

Utilizing window.matchMedia in Javascript to retain user selections during page transitions

I am encountering difficulties with the prefers-color-scheme feature and the logic I am attempting to implement. Specifically, I have a toggle on my website that allows users to override their preferred color scheme (black or light mode). However, I am fac ...

What steps are needed to set up my Express server so that it can render all my content, rather than just my HTML file?

I need help setting up a server for my project using Express. Here is the structure of my file directory: root-directory ├── public │ ├── css │ │ └── styles.css │ ├── images │ │ └── img1.png | | └ ...

Navigating through different sections of your Angular app can be easily accomplished using

My current project structure is set up like this: The application I am working on is hosted in a subdirectory called /my-scripts/vk.plants. This means that when I request this URL, it loads layout.html and returns it to the user. layout.html contains the ...

Utilizing jQuery or JavaScript to transfer information within a Bootstrap modal

I am working with a table that is generated from an SQL Table using PHP for data looping. HTML <tbody> <?php $no = 1; foreach($data_request as $data) { ?> <tr> <td class="center"><?php echo $no++.". ";?> ...

Use JavaScript's Array.filter method to efficiently filter out duplicates without causing any UI slowdown

In a unique case I'm dealing with, certain validation logic needs to occur in the UI for specific business reasons[...]. The array could potentially contain anywhere from several tens to hundreds of thousands of items (1-400K). This frontend operation ...

Implementing advanced checkbox filtering feature in React

Does anyone have experience with creating dynamic Checkbox filtering in React using Material-UI? I'm finding it challenging because the checkbox options are generated dynamically from incoming data and need to be categorized by type of Select componen ...

Utilizing v-for in Vue with TypeScript to generate multiple checkboxes

My goal was to capture the values of checkboxes and store them in an array using v-model. However, I encountered an issue where the first time I toggle a checkbox, it doesn't register. Only after checking a second box and hitting submit does the secon ...

Utilizing fluent-ffmpeg in nodejs and express to effortlessly download a video

I've been recently tackling a side project that involves downloading videos from Reddit. The tricky part is that the video and audio are stored in separate files, requiring me to merge them before being able to download them onto the client's dev ...

Ways to modify the screen when a click event occurs

To make the display block when clicking this icon: <div class="index-navi-frame-box"> <p onclick="expandFunction()"> <i class="fa fa-bars"></i> </p> </div> Here is what it should change to: <div class=" ...

Challenges arise when utilizing CSS3 animations in conjunction with transitions triggered by toggling a JavaScript class

Struggling to activate an animation while updating a class using JavaScript for a PhoneGap app. Planning on utilizing -webkit- prefixes for compatibility. However, the animations are currently unresponsive in Chrome during testing, both when applied to th ...

I am experiencing an issue where my React application is not loading the fonts when utilizing `type: 'asset/resource'` to load fonts within a CSS file. Can anyone provide guidance on

I'm encountering an issue with my webpack setup where fonts are not being loaded when using type: 'asset/resource'. Actually, there are several problems arising from the use of asset/resource, but let's focus on this particular issue fo ...

The submission of the Jquery form is not successful

I am struggling with a form on my page. I want to disable the submit button and display a custom message when submitted, then use jQuery to actually submit the form. <form> <input type="text" name="run"/> <input type=&quo ...

What is the best way to send a React prop that is buried deep within a JSON structure?

Currently, I am in the process of creating a product table to showcase items for a store. The headers of this table include: id, title, imagePath, newPrice, oldPrice. To accomplish this, I have developed an ItemTable component within my React application t ...

SecurityError: The dubious operation triggers CORS to persist in its insecurities

I have developed an HTTP server using Express in Node.js. This server is currently running locally on port 3000. There is a served HTML page called "index.html" which makes AJAX GET requests for contents (in HTML format). These AJAX contents are also serv ...

Whenever I select a link on a navigation bar, it transports me to the desired section of the page. However, I often find that the navbar ends up

Recently, I came across some website templates where clicking on a link in the navbar smoothly scrolls to the corresponding section with perfect alignment. The content at the top of the page aligns perfectly with the top of each division. Upon attempting ...

The request included an unsupported media type of "text/plain;charset=UTF-8". This caused an error in the NextJS API when interacting with Django Rest Framework

Currently diving into the world of web development, I am endeavoring to construct a website utilizing NextJS and Django Rest Framework. While NextJS effectively proxies API endpoints for retrieving data, I find myself grappling with making it work for a PO ...

Ways to make a component gradually appear and disappear in an Angular application

I have developed a task management application using Angular and I wanted to implement a fading effect for each task when it is created and before it is deleted. Despite successfully applying the fade in effect at the todo-item component level, I encounter ...

Guide on setting up a route in Next.js

Recently, I developed a simple feature that enables users to switch between languages on a webpage by adding the language code directly after the URL - i18n-next. Here's a snippet of how it functions: const [languages, ] = React.useState([{ langua ...

Unable to receive notifications within an AngularJS service

<!DOCTYPE html> <html> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <body> <div ng-app="canerApp" ng-controller="canerCtrl"> <button ng-click="click()"> ...