I have a Color picker on my website, which includes an input with the name "acf[field_65d8d325d69cb]". The value of this field changes dynamically depending on the selected color. I’m trying to make the dynamic value of this input assigned to the variable colorValue in the following code:
// Retrieve the input element based on its name
var inputElement = document.querySelector('input[name="acf[field_65d8d325d69cb]"]');
// Check if the input element is found
if (inputElement) {
// If found, assign the value to the variable colorValue
var colorValue = inputElement.value;
// Create a new style element
var styleElement = document.createElement('style');
// Set the CSS style content with the value from the input
styleElement.textContent = '.editor-styles-wrapper { --theme-palette-color-10: ' + colorValue + ' !important; }';
// Append the new style element to the head section of the document
document.head.appendChild(styleElement);
} else {
console.error('Input element not found.');
}
What I want to achieve is a dynamic change of the colorValue based on the selected color in the Color picker. How can I accomplish this?
2
Answers
Add an event listener to the input element, on change.
@chrwahl is right.
But If above answer does not work there is also another approach. I have not tested it but you can give it a try.
Now,Instead of directly reading the input value, attach an onchange event listener to the input element.
Within the event listener function, grab the new color value using inputElement.value.
Update the colorValue variable with the new value.
Use the updated colorValue to create the new style element and inject it into the head, as you already have in your code.
Here’s an example: