Adjust the hue of a figure based on the color input using JavaScript

I recently implemented a colorPicker and now I want to extract the value from it and apply it.

Here is what I have used:

 <li id="color"><input type="color" name="color" onchange="changeColor()"></li>

function changeColor(){
    var selectedShapes = document.getElementsByClassName("selected");
    var len = selectedShapes.length;
    for(var i=0; i<len; ++i)
    {
        selectedShapes[i].style.background = document.getElementsByName("color");
    }
}

The link to the file can be found here: http://jsbin.com/mebiriruzi/edit?css,js,output

Any suggestions on how to effectively utilize the user's selected color input?

Answer №1

document.getElementsByName("color")
will retrieve a list of elements indicated by the "s" in getElementsByName. An alternative approach would be to use an id and access it using
document.getElementById("color").value
, or you can select the first occurrence of "color" with
document.getElementsByName("color")[0].value

You have two options:

function changeColor(){
    var selectedShapes = document.getElementsByClassName("selected");
    var len = selectedShapes.length;
    for(var i=0; i<len; ++i)
    {
        selectedShapes[i].style.background = document.getElementsByName("color")[0].value;
    }
}

or

<li id="color"><input type="color" id="mySelectedColor" name="color" onchange="changeColor()"></li>

In your JavaScript code:

function changeColor(){
    var selectedShapes = document.getElementsByClassName("selected");
    var len = selectedShapes.length;
    for(var i=0; i<len; ++i)
    {
        selectedShapes[i].style.background = document.getElementById("mySelectedColor").value;
    }
}

Answer №2

To retrieve elements with a specific name, the getElementsByName method can be used which returns an array of matching elements. Even if only one element matches the specified name, it will still return an array. To access the first item in this array, you can use bracket notation and reference element 0 (the first element). To obtain the value of this element, you need to access the value property:

document.getElementsByName("color")[0].value

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

How can you eliminate the first elements of two or more arrays of objects until all of their first elements match based on a specific field?

My Typescript code includes a Map object called `stat_map` defined as const stat_map: Map<string, IMonthlyStat[]> = new Map(); The interface IMonthlyStat is structured as shown below (Note that there are more fields in reality) export interface IMon ...

Is there a way to call class methods from external code?

I am seeking clarification on Class files. Below is an example of a Class that I have: class CouchController { constructor(couchbase, config) { // You may either pass couchbase and config as params, or import directly into the controller ...

Toggle multiple buttons based on the data fetched in the created() lifecycle hook

I have several toggle buttons that should be selected based on the values present in the response obtained through the created() method. <li> <input v-on:click="toggleCheckbox($event)" ...

Unable to display keyboard on HTML input form in webview

Can someone assist me with displaying and allowing the keyboard to show and input properly? In my simple app, I have a main screen with buttons. When a button is clicked, it opens a webview. One of the buttons opens a webview to an HTML page with an input ...

Utilize CountUp.js to generate a dynamic timer for tracking days and hours

I am looking to create a unique counter similar to the one featured on this website https://inorganik.github.io/countUp.js/ that counts up to a specific number representing hours. My goal is to display it in a format such as 3d13h, indicating days and hour ...

Encountering a 404 error in Flask when using a '?' in a redirect

After configuring a payment service on my Flask web app, I encountered an issue where the successful payment processing redirected me to a specific URL. However, upon reaching the URL, I received an error code 404. Strangely, when I removed the "?" from th ...

Creating a gradient border around a div using CSS3

Can a border like this be achieved using only CSS, or will I need to use an image? ...

`Using top-level await in a module can interfere with the firing of the `onload` event

It seems that the load event is not triggering when I use await for an IndexedDB opening at the top level within an indirectly loaded module. Interestingly, if I remove the await, the load handler works as expected. Similarly, replacing the openDB call wi ...

Dynamic grid arrangement showcasing cells of varying heights

I am dealing with a grid layout where cells are dynamically generated using the following code: <style> .calWrapper{ width:200px; float:left; } </style> <div class="container"> <?php for($i=1; $i<=12; $i++){ echo ...

Retrieve the text content from the HTML document

I'm facing a beginner's challenge. I have a div element and I want to extract the URL from the data-element attribute into a .json file Is there a way to do this? <div content="" id="preview" data-element="http://thereislink" class="sample ...

Alexa Account Linking - Error: Account linking credentials are not valid

I've been working on setting up an Alexa skill with account linking. After obtaining the Linking Authorization Code and exchanging it for an Access Token, I attempted to input all the necessary parameters: code, access token, and skill ID into the Ale ...

Transform JSON String into Object using jQuery

Recently, I came across a JSON String in this format. {"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11‌​464"} I needed to convert it into an object structure like this [{"label":"label","label1":"67041","label2":"745"," ...

Is there a way to retrieve the response body in Express framework?

In my NodeJS API using Express, I am attempting to save the response body of a request. To achieve this, I have created two middleware functions. app.use((req, res,next) => { res.status(404).json({ errors: [{ field: "url", ...

Tips for building a carousel-style transition using React Router

I am looking to implement a carousel animation in my React Router. My website has pages named A, B, C, and D. When transitioning from page A to B, I want the animation to move from right to left. When going from B to A, I want it to move from left to rig ...

Managing form submissions using Material UI and Next.js

Can someone provide insights on using Material UI with Next Js? I am experimenting with a Login template from Material UI, but I am facing an issue where query params are added to the URL upon Submit. For example: localhost:3000/auth/login changes to: ...

get the value of the last selected element using jQuery

I am facing an issue where I cannot retrieve the selected value from my second select element. Even though I have selected the second option in the dropdown, it keeps returning the value of the first option as empty. Here is a snippet of the HTML code: & ...

Code for a regular expression that permits either letters or numbers with symbols

Here is the code snippet I am using for data validation in jQuery: return /^(?=.*[A-Za-z0-9/\$#.-_])[A-Za-z0-9/\$#.-_]$/i.test(value) The requirement is that the value should begin with letters or numbers, or a combination of both. Afterwards, ...

The xModal window will only pop up once, after which a page refresh is required

My modal window opens when a user clicks on a div, but I'm having an issue. The modal window doesn't reopen when I click on the div again. Here is my code: <div onclick="document.getElementById('id01').style.display='block&apos ...

Verify the presence of an email in MongoDB in real-time as it is being

This particular project utilizes js, mongoose, and node.js. If an email that is already in use is attempted during registration to create an account, the page will reload, all fields will be cleared, and a pop-up message using AJAX will notify the user tha ...

What is the process for assigning an element to a specific URL ID?

Imagine having an array of objects structured like this: [{ details: {id: 7}, type: minigame1, ...(more values that need to be accessed later) }, { details: {id: 8}, type: minigame1, ...(more values that need to be accessed later) }, { details: {id: ...