Home  >  Article  >  Web Front-end  >  How to Change Placeholder Color Dynamically with JavaScript?

How to Change Placeholder Color Dynamically with JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-11-19 06:01:02582browse

How to Change Placeholder Color Dynamically with JavaScript?

Manipulating Placeholder Color with JavaScript

Determining how to change a textbox's placeholder color through JavaScript can be perplexing. Although the ::placeholder selector can be used in CSS to define the placeholder color, there doesn't appear to be an immediate JavaScript equivalent.

Solution: CSS Variables

A viable solution is to leverage CSS variables. Here's how you can achieve this:

1. Define the CSS Variable:

:root {
  --placeholder-color: red;
}

This creates a CSS variable named --placeholder-color with an initial value of red.

2. Apply the Variable to the Placeholder:

::placeholder {
  color: var(--placeholder-color);
}

By referencing the --placeholder-color variable inside the ::placeholder rule, the placeholder color will now inherit the value defined in the root element.

3. Update the Variable Dynamically:

document.querySelector('input[type=text]').style.setProperty("--placeholder-color", "blue");

Using JavaScript, you can dynamically update the value of the --placeholder-color variable, which will subsequently change the color of the placeholder in all matching elements.

Example:

<input type="text" placeholder="placeholder">
<button onclick="update()">Change color</button>
function update() {
  document.querySelector('input[type=text]').style.setProperty("--placeholder-color", "blue");
}

Benefits:

  • Enables precise color changes for specific elements.
  • Allows for interactivity and dynamic updates.
  • Supports compatibility across major browsers.

The above is the detailed content of How to Change Placeholder Color Dynamically with 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