Modify the Div background color by accessing the HEX value saved in a JSON file

(I made a change to my code and removed the br tag from info2)

Currently, I have successfully implemented a feature using jQuery that reads color names and hex values from a JSON file, populates them in a drop-down select menu (which is working fine). Now, I am looking to enhance this functionality where I want the background color of a div next to the drop-down to dynamically change based on the color selected by the user. How can I achieve this?

Here's a snippet of my page:

<script language="javascript" type="text/javascript">
    
        var JSON_Response;
    
        $(document).ready(function () {
    
            $.getJSON('Colors.json', function (data) {
                JSON_Response = data;  
    
                var mySelect = document.getElementById("selColor");
    
                for (i = 0; i < JSON_Response.Colors.length; i++) {
                    var myOption = document.createElement("option");
                    myOption.text = JSON_Response.Colors[i].colorName;
                    myOption.value = i;
                    try {
    
                        mySelect.add(myOption, mySelect.options[null]);
                    }
                    catch (e) {
                        mySelect.add(myOption, null);
                    }
                } 
    
            }); 
    
            $("#selColor").change(function () {
                var myIndex = $("#selColor").val();
                $("#showColor").attr("src", JSON_Response.Colors[myIndex].hex);
    
                var info = JSON_Response.Colors[myIndex].colorName + "<br />";
                info += JSON_Response.Colors[myIndex].hex+ "<br />";
                var info2 = JSON_Response.Colors[myIndex].hex;
                $("#divDisplay").html(info).css({'background-color' : '#' + info2});
    
    
            }); 
        });     
    
        </script>
    

Answer №1

Avoid adding <br /> to the end of the info2 variable, as it should only store a hexadecimal color code.

var info2 = JSON_Response.Colors[myIndex].hex;

Answer №2

Essentially, you've got it. The mistake lies in the background-color value that you're assigning to the div.

$("#divDisplay").html(info).css({'background-color' : '#' + info2});

The correct version should be:

$("#divDisplay").html(info).css({'background-color' : '#' + JSON_Response.Colors[myIndex].hex});

Here is a basic working fiddle example

<html>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
    <button>Click me</button><br/>
    <div id="myDiv" style="height:400px;width:400px;">
    </div>

    <script>
    var hexChars = "ABCDEF0123456789";

    function getColor() {
        var colorStr = "";

        for(var idx=0; idx < 6; idx++ ) {
                colorStr += hexChars.charAt(Math.floor(Math.random() * hexChars.length));
        }

        return colorStr;
    }

    $('document').ready(function() {
        $('button').click(function() {
            var rand = getColor();

            $('#myDiv').html('#' + rand).css({ 'background-color' : '#' + rand });
        });
    });
    </script>
</body>
</html>

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

The Jquery treeview plugin allows users to easily create

For my application, I am utilizing jquery.bassistance.de/treeview/. Is there a way to configure the nodes to only expand when clicking on the '+' icon? Currently, it expands even when clicking on the text following the '+'. ...

What are the reasons for the decrease in canvas text quality when using requestAnimationFrame?

I have created a unique canvas effect where text changes color using requestAnimationFrame: var text = 'Sample text'; ctx.fillText(text,canvas_width/2,100); requestAnimationFrame(animate); function animate(time){ ctx.fillText(text,-offset,100 ...

The use of Electron require modules may lead to IntelliSense not functioning properly due to the discrepancy in working directories during runtime

Currently working on an electron-app using vs-code. I encountered some issues initially with requiring local files as modules but managed to resolve them. However, now the problem lies in the fact that I have lost intellisense for these local modules. Her ...

Commitment without anticipation of a resolution or rejection

While testing one of my AngularJs Services, I decided to write some Unit tests. Below is a sample code snippet that I have come up with: it('', function(done) { aDocument.retrieveServiceFile(extractedFileFeature) .then(function() { ...

Are you struggling with perplexing TypeScript error messages caused by a hyphen in the package name?

After creating a JavaScript/TypeScript library, my goal is for it to function as: A global variable when called from either JavaScript or TypeScript Accessible via RequireJS when called from either JavaScript or TypeScript Complete unit test coverage Th ...

What is the best way to apply a semi-transparent background to my navigation bar, while maintaining a blue background across my entire page?

Currently, I have a background set for my website along with a navigation bar that displays my name and additional information. I am looking to make the background of this navigation bar semi-transparent so that it is possible to see through it. I tried ...

How to Insert a Background Image into Advanced Custom Fields (ACF) using CSS

Hey there, I'm facing a bit of a challenge with this particular section. In the past, I've only included ACF PHP within HTML when the background image was directly in the HTML code. Now, however, I have two shapes specified in my CSS using pseudo ...

What is the best way to trigger a function once all asynchronous calls within a loop have been completed?

The function addData is called asynchronously within a loop every time reader.onloadend is triggered. const uploadFiles = () => { console.log(acceptedFiles) setLoading(true) console.log(loading) let i = 0 let l = acceptedFiles.length ...

What is the process of transforming a tree into a JSON object?

I have a tree structure that I need to convert into JSON format for use with a jquery option tree. NodeId, Title, Level 1, cars, 0 2, boats, 0 3, oldtimer, 1 4, trucks, 1 5, heavytrucks, 4 The desired tree structure is as follows: boats cars - oldtimer - ...

Passing an array to a React component retrieved through a fetch request in Redux

I am facing a challenge with returning an array to my React component from a fetch call to my Express server that I integrated into Redux. My goal is to extract and return the vitamins array from the JSON data fetched from Express: router.get('/&a ...

The Typewriter Effect does not appear alongside the heading

For my portfolio website, I am using React to create a unique typewriter effect showcasing some of my hobbies. Currently, the code is set up like this: "I like to" [hobbies] However, I want it to display like this: "I like to" [h ...

Is it better to manually input a list of select options in the user interface or retrieve them dynamically from the database in case of future changes?

Imagine designing a user interface that allows users to choose their favorite Pokemon from options like Bulbasaur, Squirtle, and Charmander. Within the database, there is a lookup table containing all possible choices: pokemon --- id name 1 Bulbasaur 2 ...

Managing special characters in PHP: Understanding charsets

While working on my website using HTML and PHP, I am having an issue with special characters (Å, Á ...) appearing as on the screen when using the post function. Strangely enough, all other HTML content displays correctly. Any suggestions for a solution ...

Create a separate server session specifically for handling an ajax request?

Currently, I am working with a collection of PHP server-side scripts that manage user session state by utilizing PHP sessions extensively for authenticated users. For the client side within a mobile application and using Jquery ajax, I am striving to esta ...

Tips for concealing the body description on the homepage of a blogger website

I want to conceal this description This is my blog and I am facing an issue where I need to hide the description on the home page. I have tried using color:white which worked initially, but when I moved the description to the top or left, the black backgro ...

The appearance of the circle in Safari is rough and lacks smoothness

My circle animation works perfectly on Google Chrome, but when I switch to Safari the edges appear faded and blurry. I tried adding "webkit" to fix it, but had no luck. Is there a compatibility issue with Safari and CSS animations? Here is my code: Snapsh ...

steps to create a personalized installation button for PWA

Looking to incorporate a customized install button for my progressive web app directly on the site. I've researched various articles and attempted their solutions, which involve using beforeinstallprompt. let deferredPrompt; window.addEventListener(& ...

Establish a pathway based on an item on the list

I need to create a functionality where I can click on a fruit in a list to open a new route displaying the description of that fruit. Can someone guide me on how to set up the route to the 'productDescription.ejs' file? app.js: const express = ...

Vue.js using the v-for directive with index

Just started using Vue.js and I have a question: I'm working with an array to create a table. When I double click on a table row, I want the program to execute a JavaScript function that will retrieve the selected item based on its index. <di ...