Home Courses Input Field Styling Using JavaScript - Change Color, Width, Margin

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:

  1. Page load
  2. Button click
  3. User interaction (like range sliders)


For example:

  1. Change text color when the page loads
  2. Adjust width using a range slider
  3. Add margin dynamically
  4. Apply multiple styles on button click


This is very useful in real-world applications where:

  1. You need to highlight validation errors
  2. Change UI dynamically
  3. Enable/disable fields or buttons
  4. 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:

  1. 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:

  1. oninput → triggers continuously while sliding
  2. onchange → 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>


Share this lesson: