Home  >  Article  >  Web Front-end  >  How Can I Dynamically Update Placeholder Color with CSS Variables in JavaScript?

How Can I Dynamically Update Placeholder Color with CSS Variables in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-14 15:11:02964browse

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:

  • Be sure to include a color picker element in your HTML to enable users to select the new placeholder color.
  • Using this technique, you can target specific placeholders by assigning unique CSS class names to the respective input elements.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn