Input Field Styling Using JavaScript - Change Color, Width, Margin
We can dynamically change the style of an input field using JavaScript based on events like:
- Page load
- Button click
- User interaction (like range sliders)
For example:
- Change text color when the page loads
- Adjust width using a range slider
- Add margin dynamically
- Apply multiple styles on button click
This is very useful in real-world applications where:
- You need to highlight validation errors
- Change UI dynamically
- Enable/disable fields or buttons
- Improve user experience
Key Concepts Covered
1. Changing Style on Page Load
When the page loads, we can directly change styles using JavaScript.
document.getElementById("user").style.color = "orange";
Important note:
- The script must be placed after the HTML elements (at the end of the
<body>), otherwise it will throw an error because the element is not yet loaded.
Changing Style on Button Click
We use a button to trigger style changes.
function handleStyle() {
let inputElStyle = document.getElementById("user").style;
inputElStyle.color = "green";
inputElStyle.width = "250px";
inputElStyle.height = "50px";
}
Changing Width Using Range Input
We use a range slider to dynamically change width.
function handleWidth(event) {
let width = event.target.value + "px";
document.getElementById("user").style.width = width;
}
Changing Margin Using Range Input
function handleMargin(event) {
let marginTop = event.target.value + "px";
document.getElementById("user").style.marginTop = marginTop;
}
Important difference:
oninput→ triggers continuously while slidingonchange→ triggers only after releasing the slider
Final Working Code
<html>
<head>
</head>
<body>
<h1>Input Field Style</h1>
<input type="text" id="user" placeholder="enter user name">
<br><br>
<button onclick="handleStyle()">Update Style</button>
<br><br>
<input oninput="handleWidth(event)" type="range" step="10" max="300" min="50">
<br><br>
<input onchange="handleMargin(event)" type="range" step="10" max="100" min="0">
<script>
// Style on page load
document.getElementById("user").style.color = "orange";
function handleStyle() {
let inputElStyle = document.getElementById("user").style;
inputElStyle.color = "green";
inputElStyle.width = "250px";
inputElStyle.height = "50px";
}
function handleWidth(event) {
let width = event.target.value + "px";
document.getElementById("user").style.width = width;
}
function handleMargin(event) {
let marginTop = event.target.value + "px";
document.getElementById("user").style.marginTop = marginTop;
}
</script>
</body>
</html>