The Web Design Group

... Making the Web accessible to all.

Welcome Guest ( Log In | Register )

> Change label color on input focus
post Jun 7 2012, 01:18 PM
Post #1

Advanced Member

Group: Members
Posts: 202
Joined: 16-November 09
Member No.: 10,346


Here's a sample form:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<title>Sample Form</title>
<form action="#">
<label for="fname">First name</label><input type="text" id="fname">
<label for="lname">Last name</label><input type="text" id="lname">

I wonder how I can change the label color when I focus/tab on its text filed? How can I do it through JavaScript if CSS doesn't work here?

Thanks in advance!
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Reply to this topicStart new topic
Christian J
post Jun 7 2012, 06:20 PM
Post #2


Group: WDG Moderators
Posts: 8,074
Joined: 10-August 06
Member No.: 7

If the INPUT comes before LABEL:

<input type="text" id="fname"><label for="fname">First name</label>

you might use this:

input:focus + label {color: red;}

Otherwise you must use javascript, e.g.:

<label for="fname">First name</label><input type="text" id="fname"

Note that there must be no linebreak or other whitespace between the LABEL and INPUT elements (since previousSibling would then apply to that whitespace node instead).

For convencience I also assume that you style the LABEL with a .focus class in a stylesheet.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post

Posts in this topic

Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:


- Lo-Fi Version Time is now: 23rd March 2019 - 10:08 AM