Home > Web Front-end > CSS Tutorial > 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
Release: 2024-11-14 15:11:02
Original
1033 people have browsed it

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>
Copy after login

CSS Code:

::placeholder {
  color: var(--placeholder-color, red);
}
Copy after login

Javascript Code:

function update() {
  const placeholderColor = document.querySelector('#color-picker').value;
  const input = document.querySelector('input[type=text]');

  input.style.setProperty("--placeholder-color", placeholderColor);
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template