Home > Article > Web Front-end > How Can I Dynamically Update Placeholder Color with CSS Variables in JavaScript?
Updating Placeholder Color with CSS Variables in Javascript
JavaScript lacks a direct method for modifying placeholder color. However, CSS variables can be utilized to achieve this effect.
HTML Code:
<input type="text" placeholder="Placeholder" /> <button onclick="update()">Change Placeholder Color</button>
CSS Code:
::placeholder { color: var(--placeholder-color, red); }
Javascript Code:
function update() { const placeholderColor = document.querySelector('#color-picker').value; const input = document.querySelector('input[type=text]'); input.style.setProperty("--placeholder-color", placeholderColor); }
In this script, the update() function retrieves the selected color from a color picker element and sets the value of the CSS variable --placeholder-color in the text input element. By referencing this variable in the CSS, the placeholder color is dynamically updated when the button is clicked.
Note:
The above is the detailed content of How Can I Dynamically Update Placeholder Color with CSS Variables in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!