How to Change Placeholder Color Dynamically with JavaScript?

Barbara Streisand
Release: 2024-11-19 06:01:02
Original
604 people have browsed it

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

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);
}
Copy after login

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");
Copy after login

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>
Copy after login
function update() {
  document.querySelector('input[type=text]').style.setProperty("--placeholder-color", "blue");
}
Copy after login

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!

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