Как изменить цвет label при активном input

On input focus I want to change the color of the label element. How can I achieve this in less? .control-label{ color: @gray-light; } .controls{ input, textarea{ background-color:re...

On input focus I want to change the color of the label element. How can I achieve this in less?

.control-label{
      color: @gray-light;
}
.controls{
  input,
  textarea{
    background-color:red; 
    &:focus{
      .control-label &{
        color: red;  //HERE
      }

    }
}

HTML:

<div class="control-group">
    <label class="control-label" for="inputEmail">Firstname</label>
    <div class="controls">
        <input type="text" id="inputEmail" placeholder="Firstname">
    </div>
</div>

Ganesh Yadav's user avatar

Ganesh Yadav

2,5572 gold badges29 silver badges52 bronze badges

asked Jan 16, 2014 at 6:19

One solution would be to use the :focus-within selector.

So, you’d do something like the below. Assuming that you always have an input of some description inside of a control-group, it will style the label whenever the input is focused on.

control-group {
    &:focus-within {
        control-label {
            color: red; 
        }
    }
}

More information can be found here: https://developer.mozilla.org/en-US/docs/Web/CSS/:focus-within

answered Mar 22, 2018 at 4:25

Michael Robinson's user avatar

3

I don’t think you can without changing your HTML, see also: Is there any way to hover over one element and affect a different element?, your elements should be direct siblings. (LESS don’t help to solve your problem here, LESS generate CSS and it seems impossible to do in CSS)

Possible suggestion:

input:focus + .control-label
{
    background-color:purple;
    color: red;
}
.controls > input
{
    float:right;
}	
<div class="controls">
    <input type="text" id="inputEmail" placeholder="Firstname">
    <label class="control-label" for="inputEmail">Firstname</label>
</div>

Or solve your problem with javascript: https://stackoverflow.com/a/20226218/1596547

Gleb Kemarsky's user avatar

answered Jan 17, 2014 at 11:30

Bass Jobsen's user avatar

Bass JobsenBass Jobsen

48.6k16 gold badges142 silver badges222 bronze badges

Use Flexbox

CSS is cascading, i.e. affected by the order that elements appear in the DOM. To be able to select the label only when the input is focused (input:focus + label), the label needs to come after the input, so;

Put the input before the label in the DOM and then use flexbox to reverse the order that they appear on the page.

.input-group {
    display: flex;
    flex-direction: column-reverse;
}

input:focus + label {
    color: green;
}
<div class="input-group">
    <input value="Input" />
    <label>Label</label>
</div>

answered Feb 26, 2019 at 20:38

brad's user avatar

bradbrad

1,28715 silver badges32 bronze badges

0

One solution would be to move the label below the input in the DOM but position them absolutely (to the parent) so the label looks to be above the input field:

<div>
  <input type="text"/>
  <label>Text</label>
</div>

In CSS move the label to the top, the input to the bottom:

label {
  position: absolute
  top: 0
}

input {
  position: absolute
  bottom: 0
}

And use the :focus state to change the style of the label:

input:focus + label {
    color: red
}

See example:

On focus, the label turns red. No JS required.

answered May 22, 2015 at 14:26

Rob Campion's user avatar

Rob CampionRob Campion

1,35913 silver badges25 bronze badges

control-group {
    &:focus-within {
        control-label {
            color: red; 
        }
    }

}

loads of hearts to this person. Nothing was working and this worked in ion-label too . Accepted answer. Stack overflow does not allow to comment (below 50 reputation). So writing seperately <3

answered Feb 25, 2021 at 12:18

Hrushikesh Sawant's user avatar

I hope I am not too late to answer this. With the new :has psudo-class we can achieve it without changing the HTML,

HTML:

<div class="control-group">
    <label class="control-label" for="inputEmail">Firstname</label>
    <div class="controls">
        <input type="text" id="inputEmail" placeholder="Firstname">
    </div>
</div>

CSS:

.control-group:has(input:focus) label{
 color: red;
}

This approach is simple and cleaner.

Note: it is not supported by firefox yet.

answered Nov 17, 2022 at 5:40

Harsh Behl's user avatar

1

The easy way is to use :focus-within check developer mozilla

.control-group:focus-within .control-label {
   color: red;
}

Or

.control-group:focus-within label {
   color: red;
}

answered Jul 1, 2020 at 8:52

ayobami john's user avatar

Cover image for I can CSS a focused input, but what about its label?

Timothy Foster

Welcome to Stackazon, your one-stop shop for great solutions to tricky coding problems! Your search query, «How do I style a label when its input is focused?«, has returned five results.

Our ratings for this query consider browser compatibility, accessibility, and complexity. Be sure to read our reviewers’ opinions for additional resources and justification for the rating.

The best part about Stackazon? Everything is free, and delivery is instant! No prime subscription needed either!

Disclaimer: The people, ratings, and reviews are fictional and based on my opinion and knowledge of key factors. What solution is best always depends on context and your use case!

This is mostly my wacky way of demonstrating how to evaluate important factors when coding for the web 😊

  • The Problem
  • Solutions

    • Using Adjacent Siblings (🌕🌕🌕🌗🌑)
    • Using Javascript (🌕🌕🌕🌘🌑)
    • Using :focus-within with Explicit Labels (🌕🌕🌕🌕🌘)
    • Using :focus-within with Implicit Labels (🌕🌕🌕🌕🌑)
    • Using :has (🌖🌑🌑🌑🌑)
  • Codepen

Why do you use moons instead of stars?

Here at Stackazon, we rate using moons instead of stars because emoji sets support different moon phases, which can indicate fractional rating! Thank you, Moon, for having such convenient phases ❤️

The Problem

Most of the time, an HTML input element should be properly labeled.

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

Enter fullscreen mode

Exit fullscreen mode

But let’s say you want to highlight the «Name» label if someone is typing stuff into its text field. As web developers, we can use CSS to customize how the input looks when focused:

input:focus {
    border-color: red;
}

Enter fullscreen mode

Exit fullscreen mode

But… how do you do the same for the label? Turns out it’s tricky!

Solutions

Our Stackazon reviewers reference the following resources (and we recommend that you do too when evaluating solutions for other issues!):

  • Can I Use — Tracks the browser compatibility of various web features
  • Accessibility Support — Tracks to what degree assistive technologies implement accessibility specifications
  • Web Content Accessibility Guidelines — Essentially a specification for maximizing web accessibility, also called WCAG
  • MDN Web Docs — Curated documentation of web features including best practices (and recently got an upgrade!)

Using Adjacent Siblings

Rating: 🌕🌕🌕🌗🌑

CSS provides an adjacent sibling combinator which lets you match an element that is directly after another element.

If you structure your HTML such that the label is directly after the input:

<div class="input-container">
    <input id="name" type="text" />
    <label for="name">Name</label>
</div>

Enter fullscreen mode

Exit fullscreen mode

Then you can style the label with the adjacent sibling combinator:

input:focus + label {
    color: red;
}

Enter fullscreen mode

Exit fullscreen mode

However, for a text field, conventionally the label is supposed to come before the input.

A text input field is followed by a label, 'First Name'.

When the label comes after the text input field, it looks strange.

Unfortunately, the fancy adjacent sibling plus sign only works top-to-bottom! If you try to use label + input:focus, then the styles will only apply to the input directly and not the label. If the label comes first in the markup, then you can’t use this combinator to select the label when the input is focused.

That said, CSS to the rescue again! CSS can visually reorder elements on the page:

.input-container {
    display: flex;
}

input { order: 2; }
label { order: 1; }

Enter fullscreen mode

Exit fullscreen mode

Reviews

Our reviewers gave this solution 3.5 out of 5 moons, citing excellent browser compatibility but with some accessibility concerns.

Ivan Eaton says:

Of the solutions presented, this has the best browser compatibility, as the adjacent sibling combinator has been implemented in all major browsers, included Internet Explorer, for many years.

Flexbox, though newer, is also widely supported.

See: W3C Selectors Level 4

Serena Redmon says:

I am concerned about how screen readers announce the text field and its label. Visually, it looks like the label comes first since we used the order property, but the screen reader announces the input first instead since it is first in the HTML code.

The Web Content Accessibility Guidelines (WCAG) stipulate that order of content in the source code [should be] the same as the visual presentation of the content in order to minimize confusion when using accessibility tools. Therefore, I’ve rated this solution lower as the adjacency combinator requires the elements be in unconventional order.

See: WCAG on Making the DOM order match the visual order

Using Javascript

Rating: 🌕🌕🌕🌘🌑

When an input is focused or unfocused, it emits an event which we can listen to with Javascript. Additionally, the element has a reference to all of its labels via the labels property. Therefore, we can leverage Javascript with the following strategy:

  1. When the input receives focus, add a focused class to its label.
  2. When the input loses focus (called blurring), remove the focused class.
document.querySelectorAll('input').forEach(input => {
  input.addEventListener('focus', () => {
    input.labels.forEach(label => {
      label.classList.add('focused')
    })
  })

  input.addEventListener('blur', () => {
    input.labels.forEach(label => {
      label.classList.remove('focused')
    })
  })
})

Enter fullscreen mode

Exit fullscreen mode

And now with CSS, you just need to apply styles to the focused class!

.focused {
    color: red;
}

Enter fullscreen mode

Exit fullscreen mode

Reviews

Our reviewers gave this solution 3.25 out of 5 moons, citing some browser compatibility issues and complexity as a result of using Javascript.

Ivan Eaton says:

The strategy of leveraging Javascript bypasses all the potential problems with browser compatibility for CSS features, but exchanges that for problems in Javascript feature support.

More specifically, the labels property with this solution uses is not supported in IE 11 and can result in errors if not handled. To maximize compatibility while still using this general approach, I recommend reading how to find an input’s associated label.

See: Can I Use HTMLInputElement labels

Jose Scott says:

Introducing Javascript when there are decent CSS-only solutions can feel like overkill. The Javascript here introduces the need to properly manage when and how listeners are added to inputs, which requires some care for sufficiently dynamic pages and forms.

That said, this solution may be preferred if an input has many labels or the input and its label are far apart in the HTML hierarchy such that it is difficult to use CSS selectors to style them.

Using :focus-within with Explicit Labels

Rating: 🌕🌕🌕🌕🌘

CSS offers a relatively new pseudo-class called :focus-within which matches an element if it or any of its descendants have focus. Therefore, as long as the label and its input share a common parent element in HTML, we can use this to style the label:

<div class="input-container">
    <label for="name-field">Name</label>
    <input id="name-field" type="text" />
</div>

Enter fullscreen mode

Exit fullscreen mode

.input-container:focus-within label {
    color: red;
}

Enter fullscreen mode

Exit fullscreen mode

This works since the focused input is within the input-container div. The selector is essentially saying, «find an input container with focus somewhere inside of it, then find all the container’s child labels.»

Of note, we are using the label’s for attribute to associate it to an input. If the input has an id defined, setting for to equal that id creates the relationship. Notice that in the HTML code above, both for and id are «name-field». This is often called an explicit label.

For more on explicit labels and their counterpart, implicit labels, read Labeling Controls.

Reviews

Our reviewers gave this solution 4.25 out of 5 moons, citing lack of support in old browsers but having the best accessibility of solutions present.

Ivan Eaton says:

Although a simple solution, :focus-within is not supported in IE 11. In a world that is moving away from that old browser, this solution becomes better and better, but unfortunately I cannot recommend it to everyone.

See: Can I use :focus-within

Serena Redmon says:

Of solutions presented, this supports accessibility tools the best: it properly assigns a label to an input and keeps code-order and visual-order the same, both being WCAG requirements.

Using :focus-within with Implicit Labels

Rating: 🌕🌕🌕🌕🌑

Instead of having a containing div, the label is able to contain its associated input directly.

<label>Name
    <input type="text" />
</label>

Enter fullscreen mode

Exit fullscreen mode

With this structure, the :focus-within pseudo-class, which matches an element if it or any of its descendants have focus, can be applied directly on the label. When the input inside of it has focus, then the label receives the styling we want.

label:focus-within {
    color: red;
}

Enter fullscreen mode

Exit fullscreen mode

Associating a label and input via hierarchy like this, as opposed to using the input’s id, creates what’s called an implicit label, in contrast to explicit labels in the other solutions.

Reviews

Our reviewers gave this solution 4 out of 5 moons, citing minor accessibility issues and lack of support in old browsers.

Serena Redmon says:

Implicit labels are best used when the id of the input is not known and hence an explicit label cannot be created. This is because, generally, explicit labels are better supported by assistive technology (Ref: Labeling Controls). That said, support has gotten better with time.

For example, as of today, most screen readers now equally support implicit labels and explicit labels. However, voice control software, which can be used by people with movement disabilities preventing them from using a keyboard or mouse, does not always adequately support implicit labels.

See: Accessibility Support for labels

Ivan Eaton says:

Although a simple solution, :focus-within is not supported in IE 11. In a world that is moving away from that old browser, this solution becomes better and better, but unfortunately I cannot recommend it to everyone.

See: Can I use :focus-within

Using :has

Rating: 🌖🌑🌑🌑🌑

A notorious fact about CSS is there is no way to style an element based on elements after it in HTML. So for example, you can’t style a quote that contains a link differently than a quote that doesn’t, and more relevantly you can’t style a label whose input directly after it is focused.

At least, that’s true for now: Introducing the :has() pseudo-class!

This pseudo-class matches the element if the selector provided as a parameter also matches. The inner selector is relative to the element with the :has on it.

label:has(+ input:focus) {
    color: red;
}

Enter fullscreen mode

Exit fullscreen mode

This says «select labels that have an adjacent sibling which is a focused input». Unlike the Using Adjacent Siblings solution, this does not style the input. This styles the label, exactly what we want.

What’s neat about this solution is that the label gets to come before its input and it doesn’t require a containing div.

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

Enter fullscreen mode

Exit fullscreen mode

Reviews

Our reviewers gave this solution 0.75 out of 5 moons, citing its experimental status as rendering it unusable for now.

Ivan Eaton says:

Currently, nothing except the newest version of Safari supports this selector, making it impossible to use. Thankfully, Chrome has a proposal out, so maybe someday in the future we’ll see this added more universally!

See: Can I Use :has

Codepen

I would like to incorporate a form focus feature where it changes the
color of each icon when you focus on that specific field

<div id="rightside">
            <div th:replace="fragments/loginform">
            <form method="post" id="login" th:object="${credential}">
     <p id="errors" class="warning" role="alert">
            <span th:each="err : ${#fields.errors('*')}" th:utext="${err}"/>
        </p>      
     <p id="block">

       <label for="username" class="has-feedback"><i class="fa fa-user" aria-hidden="true"></i></label>   

       <span th:if="${openIdLocalId}">
                <strong>
                    <span th:utext="${openIdLocalId}"/>
                </strong>
                <input type="hidden"
                       id="username"
                       name="username"
                       th:value="${openIdLocalId}"/>
            </span>

            <span th:unless="${openIdLocalId}">
                <input class="required textinput has-feedback"
                       placeholder="UH Username"
                       id="username"
                       size="14"
                       tabindex="1"
                       type="text"
                       th:field="*{username}"
                       th:accesskey="#{screen.welcome.label.netid.accesskey}"
                       autocomplete="off"
                       autocapitalize="off"
                       autocorrect="off"
                       required="required"
                       autofocus="autofocus"
                />
            </span>
       </p> 

      <p id="block">
        <label for="password" class="fontawesome-lock"><i class="fa fa-lock" aria-hidden="true"></i></label> 

                <input class="required textinput"                       
                       placeholder="Password"
                       type="password"
                       id="password"
                       name="password"
                       size="14"
                       tabindex="2"
                       th:accesskey="#{screen.welcome.label.password.accesskey}"
                       th:field="*{password}"
                       autocomplete="off"
                       required="required"                   
                 />                                     
      </p>

Here is the CSS

#rightside {
    margin-top: 15px;
    float: left;
    width: 70%;
}
#rightside h3 {
    font-size: 110%;
}
#rightside a {
    display: block;
}
#rightside input.textinput {
    width: 60%;
    float: left;
    padding-left: 5px;
    height: 35px;
    border-radius: 7px;
}
#rightside input.textinput:focus {
    outline-width: 0;
}
#rightside form label {
    background-color: #e1e1e1;
    border-radius: 8px 0px 0px 8px;
    border: solid 1px #CCC;
    border-right: 1px solid #CCC;
    color: #000;
    display: block;
    float: left;
    line-height: 50px;
    text-align: center;
    font-size: 20px;
    width: 15%;
    height: 50px;
}
#rightside form input[type="text"] {
    float: left;
    background-color: #fff;
    border-radius: 0px 8px 8px 0px;
    color: #000;
    padding: 0 3%;
    width: 77%;
    height: 50px;
}
#rightside form input[type="password"] {
    float: left;
    background-color: #fff;
    border-radius: 0px 8px 8px 0px;
    color: #000;
    padding: 0 3%;
    width: 77%;
    height: 50px;
}
#rightside form input[type="submit"] {
    float: left;
    background: #e1e1e1;
    width: 99%;
    height: 50px;
    border-radius: 5px;
    border: solid 1px #978257;
    margin-bottom: 1.5em;
    color: black;
    cursor: pointer;
    transition: background 0.3s ease-in-out;
    font-weight: 600;
}
#rightside form input[type="submit"]:hover {
    background: #b6985a;
    color: #fff;
}

When the user focuses on either text field, the font-awesome icon pertaining to that input field should change color. Any help would be great! Thanks! CSS only would be preferable, but a js would work too

asked Nov 30, 2016 at 20:53

Hicks's user avatar

I went ahead and made a codepen for you to show you the value of the following blog post:

Highlight Related Label when Input in Focus

Here’s what it offers:

$("form :input").focus(function() {
  $("label[for='" + this.id + "']").addClass("labelfocus");
}).blur(function() {
  $("label").removeClass("labelfocus");
});

The above utilizes jQuery and it works well as a conceptual example.

If you wanted to do something that leverages CSS‘s :focus then I would suggest you change your markup to allow something like a sibling (~), adjacent/following sibling (+) or even a descendant selector if you wrap your input in the label.

The key here is to associate your label‘s icon (<i>) with your input element.

answered Nov 30, 2016 at 21:19

MassDebates's user avatar

MassDebatesMassDebates

9276 silver badges10 bronze badges

You can play with :focus and :blur pseudo-classes

$(document).ready(function(){
    $(".username").focus(function(){
        $(".fa-user").css("color","red");
        console.log("in");
    }).blur(function() {
        $(".fa-user").css("color","yellow");
        console.log('out');
    });

    $(".password").focus(function(){
        $(".fa-lock").css("color","red");
        console.log("in");
    }).blur(function() {
        $(".fa-lock").css("color","yellow");
        console.log('out');
    });


});

https://jsfiddle.net/czs3sy0a/2/

answered Nov 30, 2016 at 21:27

Yuri Ramos's user avatar

Yuri RamosYuri Ramos

1,92517 silver badges23 bronze badges

I have created a pen that sets a highlighted class on the parent p, and colors the icon using this CSS:

p.highlighted .fa {color: red;}

And this JS:

$(function() {
    $('input').focusin(function() {
      $(this).parent().parent().addClass('highlighted');
    });
    $('input').focusout(function() {
      $(this).parent().parent().removeClass('highlighted');
    });
});

answered Nov 30, 2016 at 21:28

Mr. Hugo's user avatar

Mr. HugoMr. Hugo

11.3k3 gold badges37 silver badges57 bronze badges

Here is a pure css solution you can use. As we know we dont have any way to select parent element along with css but we can get the next sibling element with the ‘+’ selector. So what i have done is placed the label containing the icon right after the input that will change it’s color when focused using the css :focus pseudo element along with the ‘+’ selector of css to get the icon in the label next to the input focused.

In order to set the positions correctly after moving the labels in front of the inputs. I changed the input and label css class from float:left to float:right. This aligned them where label came before input and the width percentage i changed from 77% to 75% just to keep the responsiveness correct on smaller screens. Below is the sample code.

Sample Code: http://codepen.io/Nasir_T/pen/VmrgWw

Hope this helps you and any future coders who do not want work with a JS code solution.

answered Nov 30, 2016 at 21:59

Nasir T's user avatar

Nasir TNasir T

2,5731 gold badge9 silver badges15 bronze badges

0

I would like to incorporate a form focus feature where it changes the
color of each icon when you focus on that specific field

<div id="rightside">
            <div th:replace="fragments/loginform">
            <form method="post" id="login" th:object="${credential}">
     <p id="errors" class="warning" role="alert">
            <span th:each="err : ${#fields.errors('*')}" th:utext="${err}"/>
        </p>      
     <p id="block">

       <label for="username" class="has-feedback"><i class="fa fa-user" aria-hidden="true"></i></label>   

       <span th:if="${openIdLocalId}">
                <strong>
                    <span th:utext="${openIdLocalId}"/>
                </strong>
                <input type="hidden"
                       id="username"
                       name="username"
                       th:value="${openIdLocalId}"/>
            </span>

            <span th:unless="${openIdLocalId}">
                <input class="required textinput has-feedback"
                       placeholder="UH Username"
                       id="username"
                       size="14"
                       tabindex="1"
                       type="text"
                       th:field="*{username}"
                       th:accesskey="#{screen.welcome.label.netid.accesskey}"
                       autocomplete="off"
                       autocapitalize="off"
                       autocorrect="off"
                       required="required"
                       autofocus="autofocus"
                />
            </span>
       </p> 

      <p id="block">
        <label for="password" class="fontawesome-lock"><i class="fa fa-lock" aria-hidden="true"></i></label> 

                <input class="required textinput"                       
                       placeholder="Password"
                       type="password"
                       id="password"
                       name="password"
                       size="14"
                       tabindex="2"
                       th:accesskey="#{screen.welcome.label.password.accesskey}"
                       th:field="*{password}"
                       autocomplete="off"
                       required="required"                   
                 />                                     
      </p>

Here is the CSS

#rightside {
    margin-top: 15px;
    float: left;
    width: 70%;
}
#rightside h3 {
    font-size: 110%;
}
#rightside a {
    display: block;
}
#rightside input.textinput {
    width: 60%;
    float: left;
    padding-left: 5px;
    height: 35px;
    border-radius: 7px;
}
#rightside input.textinput:focus {
    outline-width: 0;
}
#rightside form label {
    background-color: #e1e1e1;
    border-radius: 8px 0px 0px 8px;
    border: solid 1px #CCC;
    border-right: 1px solid #CCC;
    color: #000;
    display: block;
    float: left;
    line-height: 50px;
    text-align: center;
    font-size: 20px;
    width: 15%;
    height: 50px;
}
#rightside form input[type="text"] {
    float: left;
    background-color: #fff;
    border-radius: 0px 8px 8px 0px;
    color: #000;
    padding: 0 3%;
    width: 77%;
    height: 50px;
}
#rightside form input[type="password"] {
    float: left;
    background-color: #fff;
    border-radius: 0px 8px 8px 0px;
    color: #000;
    padding: 0 3%;
    width: 77%;
    height: 50px;
}
#rightside form input[type="submit"] {
    float: left;
    background: #e1e1e1;
    width: 99%;
    height: 50px;
    border-radius: 5px;
    border: solid 1px #978257;
    margin-bottom: 1.5em;
    color: black;
    cursor: pointer;
    transition: background 0.3s ease-in-out;
    font-weight: 600;
}
#rightside form input[type="submit"]:hover {
    background: #b6985a;
    color: #fff;
}

When the user focuses on either text field, the font-awesome icon pertaining to that input field should change color. Any help would be great! Thanks! CSS only would be preferable, but a js would work too

asked Nov 30, 2016 at 20:53

Hicks's user avatar

I went ahead and made a codepen for you to show you the value of the following blog post:

Highlight Related Label when Input in Focus

Here’s what it offers:

$("form :input").focus(function() {
  $("label[for='" + this.id + "']").addClass("labelfocus");
}).blur(function() {
  $("label").removeClass("labelfocus");
});

The above utilizes jQuery and it works well as a conceptual example.

If you wanted to do something that leverages CSS‘s :focus then I would suggest you change your markup to allow something like a sibling (~), adjacent/following sibling (+) or even a descendant selector if you wrap your input in the label.

The key here is to associate your label‘s icon (<i>) with your input element.

answered Nov 30, 2016 at 21:19

MassDebates's user avatar

MassDebatesMassDebates

9276 silver badges10 bronze badges

You can play with :focus and :blur pseudo-classes

$(document).ready(function(){
    $(".username").focus(function(){
        $(".fa-user").css("color","red");
        console.log("in");
    }).blur(function() {
        $(".fa-user").css("color","yellow");
        console.log('out');
    });

    $(".password").focus(function(){
        $(".fa-lock").css("color","red");
        console.log("in");
    }).blur(function() {
        $(".fa-lock").css("color","yellow");
        console.log('out');
    });


});

https://jsfiddle.net/czs3sy0a/2/

answered Nov 30, 2016 at 21:27

Yuri Ramos's user avatar

Yuri RamosYuri Ramos

1,92517 silver badges23 bronze badges

I have created a pen that sets a highlighted class on the parent p, and colors the icon using this CSS:

p.highlighted .fa {color: red;}

And this JS:

$(function() {
    $('input').focusin(function() {
      $(this).parent().parent().addClass('highlighted');
    });
    $('input').focusout(function() {
      $(this).parent().parent().removeClass('highlighted');
    });
});

answered Nov 30, 2016 at 21:28

Mr. Hugo's user avatar

Mr. HugoMr. Hugo

11.3k3 gold badges37 silver badges57 bronze badges

Here is a pure css solution you can use. As we know we dont have any way to select parent element along with css but we can get the next sibling element with the ‘+’ selector. So what i have done is placed the label containing the icon right after the input that will change it’s color when focused using the css :focus pseudo element along with the ‘+’ selector of css to get the icon in the label next to the input focused.

In order to set the positions correctly after moving the labels in front of the inputs. I changed the input and label css class from float:left to float:right. This aligned them where label came before input and the width percentage i changed from 77% to 75% just to keep the responsiveness correct on smaller screens. Below is the sample code.

Sample Code: http://codepen.io/Nasir_T/pen/VmrgWw

Hope this helps you and any future coders who do not want work with a JS code solution.

answered Nov 30, 2016 at 21:59

Nasir T's user avatar

Nasir TNasir T

2,5731 gold badge9 silver badges15 bronze badges

0

The <label> HTML element represents a caption for an item in a user interface.

Try it

Associating a <label> with a form control, such as <input> or <textarea> offers some major advantages:

  • The label text is not only visually associated with its corresponding text input; it is programmatically associated with it too. This means that, for example, a screen reader will read out the label when the user is focused on the form input, making it easier for an assistive technology user to understand what data should be entered.
  • When a user clicks or touches/taps a label, the browser passes the focus to its associated input (the resulting event is also raised for the input). That increased hit area for focusing the input provides an advantage to anyone trying to activate it — including those using a touch-screen device.

To explicitly associate a <label> element with an <input> element, you first need to add the id attribute to the <input> element. Next, you add the for attribute to the <label> element, where the value of for is the same as the id in the <input> element.

Alternatively, you can nest the <input> directly inside the <label>, in which case the for and id attributes are not needed because the association is implicit:

<label>
  Do you like peas?
  <input type="checkbox" name="peas" />
</label>

The form control that a label is labeling is called the labeled control of the label element. Multiple labels can be associated with the same form control:

<label for="username">Enter your username:</label>
<input id="username" name="username" type="text" />
<label for="username">Forgot your username?</label>

Elements that can be associated with a <label> element include <button>, <input> (except for type="hidden"), <meter>, <output>, <progress>, <select> and <textarea>.

Attributes

This element includes the global attributes.

for

The value of the for attribute must be a single id for a labelable form-related element in the same document as the <label> element. So, any given label element can be associated with only one form control.

Note: To programmatically set the for attribute, use htmlFor.

The first element in the document with an id attribute matching the value of the for attribute is the labeled control for this label element — if the element with that id is actually a labelable element. If it is not a labelable element, then the for attribute has no effect. If there are other elements that also match the id value, later in the document, they are not considered.

Multiple label elements can be given the same value for their for attribute; doing so causes the associated form control (the form control that for value references) to have multiple labels.

Note: A <label> element can have both a for attribute and a contained control element, as long as the for attribute points to the contained control element.

Styling with CSS

There are no special styling considerations for <label> elements — structurally they are simple inline elements, and so can be styled in much the same way as a <span> or <a> element. You can apply styling to them in any way you want, as long as you don’t cause the text to become difficult to read.

Examples

Defining an implicit label

<label>Click me <input type="text" /></label>

Defining an explicit label with the «for» attribute

<label for="username">Click me to focus on the input field</label>
<input type="text" id="username" />

Accessibility concerns

Interactive content

Don’t place interactive elements such as anchors or buttons inside a label. Doing so makes it difficult for people to activate the form input associated with the label.

Don’t

<label for="tac">
  <input id="tac" type="checkbox" name="terms-and-conditions" />
  I agree to the <a href="terms-and-conditions.html">Terms and Conditions</a>
</label>

Do

<label for="tac">
  <input id="tac" type="checkbox" name="terms-and-conditions" />
  I agree to the Terms and Conditions
</label>
<p>
  <a href="terms-and-conditions.html">Read our Terms and Conditions</a>
</p>

Headings

Placing heading elements within a <label> interferes with many kinds of assistive technology, because headings are commonly used as a navigation aid. If the label’s text needs to be adjusted visually, use CSS classes applied to the <label> element instead.

If a form, or a section of a form needs a title, use the <legend> element placed within a <fieldset>.

Don’t

<label for="your-name">
  <h3>Your name</h3>
  <input id="your-name" name="your-name" type="text" />
</label>

Do

<label class="large-label" for="your-name">
  Your name
  <input id="your-name" name="your-name" type="text" />
</label>

Buttons

An <input> element with a type="button" declaration and a valid value attribute does not need a label associated with it. Doing so may actually interfere with how assistive technology parses the button input. The same applies for the <button> element.

Technical summary

Content categories Flow content,
phrasing content,
interactive content,
form-associated element, palpable content.
Permitted content Phrasing content, but no descendant label elements. No
labelable
elements other than the labeled control are allowed.
Tag omission None, both the starting and ending tag are mandatory.
Permitted parents Any element that accepts
phrasing content.
Implicit ARIA role No corresponding role
Permitted ARIA roles No role permitted
DOM interface HTMLLabelElement

Specifications

Specification
HTML Standard
# the-label-element

Browser compatibility

BCD tables only load in the browser

Изменить цвет метки на активном поле ввода

Кто-нибудь знает, почему это не работает? Я хочу изменить цвет метки в поле ввода, когда поле активно.

JavaScript:

$("input").focus(function() {
var inputID = document.activeElement.id;
document.getAnonymousElementByAttribute('label','for', inputID).setAttribute('class', 'active');
});

HTML:

<label for="username">Username</label>
<input name="username" id="username" type="text"><br>
<label for="passwort">Passwort</label>
<input name="passwort" id="passwort" type="password"><br>
<input type="submit" class="button" value="login">

CSS:

.active{
    color: #FFA500 !important;
}

Я надеюсь, что кто-то может мне помочь :)

С вашим текущим HTML:

$('input').focus(function(){
    $(this).prev().addClass('active');
}).blur(function(){
    $(this).prev().removeClass('active');
});

Демо JS Fiddle.

Или с on() (при условии, что вы используете jQuery 1.7 или выше):

$('input').on('focus blur', function(e){
    var prev = $(this).prev();
    prev[e.type == 'focus' ? 'addClass' : 'removeClass']('active');
});

Демо JS Fiddle.

Более абстрактный (поэтому структура HTML не имеет значения), выбор по for атрибут:

$('input').on('focus blur', function(e){
    var label = $('label[for="' + this.id + '"]');
    label[e.type == 'focus' ? 'addClass' : 'removeClass']('active');
});

Демо JS Fiddle.

Ссылки:

  • addClass().
  • Атрибут-равно ([attribute="value"]) селектор.
  • blur().
  • focus().
  • on().
  • prev().
  • removeClass().

Создан 22 сен.

$('input').on('click', function(){
    $(label).toggleClass('active');
});

Вы слишком усложняете вещи, будьте проще, иногда самый полезный инструмент разработчиков — это клавиша возврата.

Создан 22 сен.

Пытаться input:focus вместо .active в вашем CSS-коде. Пропускать !important так же.

input:focus{
   color: #FFA500;
}

Создан 22 сен.

Вы смешиваете функции jQuery с не-jQuery. Попробуйте использовать только функции jQuery для решения вашей задачи. В моем примере ниже я изменил .focus() в .on('focus',callback) что то же самое, но просто более понятно. В jQuery вы должны получить цель своего события и обернуть ее $(). Вы также можете использовать this но я стараюсь не использовать его по нескольким причинам. Затем вы можете применить любой из многих методов jQuery:

$("input").on('focus', function(ev) {
    var t = $(ev.target);
    t.addClass('active');
});

Создан 22 сен.

См. здесь очень простой пример: http://jsfiddle.net/zn5fB/

И здесь, для примера, запускаемого событием: http://jsfiddle.net/zn5fB/1/

Установка стиля с помощью JavaScript обычно имеет следующий формат:

document.getElementById("abc").style.[css property name in camel case] = "[value]";

Вы обнаружите, что очень часто используется такая библиотека, как JQuery чтобы сделать это (и многое другое) немного проще. С помощью jQuery вы можете написать такой код:

// find all elements with the tag name "bar" that are direct 
// descendants of an element with the class name "foo"
$(".foo > BAR").css("color", "red");

ответ дан 24 окт ’17, 02:10

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками

javascript
html
css

or задайте свой вопрос.

By

rus · Posted December 17, 2022

html:
 

<td>
<span class=»qty-minus» onclick=»qtyMinus(); return false;» data-id=»<?=$id;?>» data-qty=»<?= $item[‘qty’];?>» data-weight=»<?=$item[‘weight’];?>»>
<i class=»bi bi-dash-circle-fill text-success»></i>
</span>
<span class=»qty»><?= $item[‘qty’];?></span>
<span class=»qty-plus» onclick=»qtyPlus(); return false;» data-id=»<?=$id;?>» data-qty=»<?= $item[‘qty’];?>» data-weight=»<?=$item[‘weight’];?>»>
<i class=»bi bi-plus-circle-fill text-success»></i>
</span>
</td>

js:
 

// Изменение количества товара в заказа — плюс
function qtyPlus() {
$(‘.qty-plus’).on(‘click’, function(){
let str = $(this).data(‘id’);
if(typeof str === ‘string’){
let id_arr = str.split(‘-‘),
id = id_arr[0],
mod = id_arr[1],
qty_update = $(this).data(‘qty’)+1,
weight = $(this).data(‘weight’);
$.ajax({
url: ‘/cart/add’,
data: {id: id, qty_update: qty_update, mod: mod, weight:weight},
type: ‘GET’,
success: function(res){
showCart(res);
},
error: function(){
alert(‘Ошибка! Попробуйте позже’);
}
});
}else if(!Number.isNaN(str)){
let id = $(this).data(‘id’),
mod = null,
qty_update = $(this).data(‘qty’)+1,
weight = $(this).data(‘weight’);
$.ajax({
url: ‘/cart/add’,
data: {id: id, qty_update: qty_update, mod: mod, weight:weight},
type: ‘GET’,
success: function(res){
showCart(res);
},
error: function(){
alert(‘Ошибка! Попробуйте позже’);
}
});
}
});
return true;
}
// Изменение количества товара в заказа — минус
function qtyMinus() {
$(‘.qty-minus’).on(‘click’, function(){
let str = $(this).data(‘id’);
if(typeof str === ‘string’){
let id_arr = str.split(‘-‘),
id = id_arr[0],
mod = id_arr[1],
qty_update = $(this).data(‘qty’)-1,
weight = $(this).data(‘weight’);
$.ajax({
url: ‘/cart/add’,
data: {id: id, qty_update: qty_update, mod: mod, weight:weight},
type: ‘GET’,
success: function(res){
showCart(res);
},
error: function(){
alert(‘Ошибка! Попробуйте позже’);
}
});
}else if(!Number.isNaN(str)){
let id = $(this).data(‘id’),
mod = null,
qty_update = $(this).data(‘qty’)-1,
weight = $(this).data(‘weight’);
$.ajax({
url: ‘/cart/add’,
data: {id: id, qty_update: qty_update, mod: mod, weight:weight},
type: ‘GET’,
success: function(res){
showCart(res);
},
error: function(){
alert(‘Ошибка! Попробуйте позже’);
}
});
}
});
return true;
}

Суть в том, что клик срабатывает только со второго раза… Почему?
Страница: https://shop-site.su/category/men

Нужно положить товар в корзину и либо в модальном окне, либо перейти на страницу оформления заказа (а лучше и там и там покликать) и покликать на плюс и минус кол-ва товара.

Решил проблему:
убрал из html вызов функции onclick=»qtyMinus(); return false;»

а js переделал вот так:
$(‘body’).on(‘click’, ‘.qty-minus’, function(){…});

Но вот ответ на вопрос почему, все же хотелось бы знать.

Подсказки в полях формы помогают пользователю понять, какие данные ему надо вводить. Для <input> есть атрибут placeholder, он выводит в поле текст, который исчезает при наборе текста. С помощью псевдокласса :focus и псевдоэлемента ::placeholder можно изменить вид подсказки, чтобы при получении фокуса она сдвигалась вверх и уменьшалась (рис. 1).

Изменение вида подсказки

Рис. 1. Изменение вида подсказки

Стиль подсказки устанавливается через селектор ::placeholder — зададим серый цвет текста с помощью свойства color и время трансформации через transition.

input::placeholder {
  transition: 0.5s; /* Время трансформации */
  color: #aaa; /* Цвет подсказки */
}

Вид подсказки при получении полем фокуса устанавливается через селектор :focus::placeholder. В стилевых правилах зададим размер шрифта через свойство font-size и переместим подсказку через transform с функцией translateY. Отрицательное значение сдвинет подсказку вверх.

input:focus::placeholder { 
  font-size: 10px; /* Размер шрифта */
  transform: translateY(-16px); /* Сдвигаем вверх */
}

Остальной код нужен для красоты и приведён в примере 1.

Пример 1. Изменение подсказки при фокусе

<!DOCTYPE html>
<html>
<head>
<meta charset=»utf-8″>
<title>:focus</title>
<style>
form {
background: #f5f5f5; /* Цвет фона */
width: 300px; /* Ширина формы */
margin: auto; /* Выравниваем по центру */
padding: 20px; /* Поля вокруг текста */
}
input {
width: 100%; /* Ширина поля */
box-sizing: border-box; /* Ширина не учитывает padding */
margin: 10px 0; /* Отступы сверху и снизу */
padding: 12px 0; /* Поля вокруг текста */
border: none; /* Убираем рамку */
border-bottom: 1px solid #ccc; /* Линия снизу */
background: transparent; /* Прозрачный фон */
}
input:focus {
outline: none; /* Убираем контур */
border-bottom: 2px solid #1976D2; /* Синяя линия снизу */
}
input::placeholder {
transition: 0.5s; /* Время трансформации */
color: #aaa; /* Цвет подсказки */
}
input:focus::placeholder {
font-size: 10px; /* Размер шрифта */
transform: translateY(-16px); /* Сдвигаем вверх */
}
</style>
</head>
<body>
<form action=»/example/handler.php»>
<input type=»text» name=»login» placeholder=»Логин»>
<input type=»password» name=»pass» placeholder=»Пароль»>
</form>
</body>
</html>

К сожалению, данный вариант не является универсальным и не работает желаемым образом в браузерах Internet Explorer и Firefox. Так что приведём альтернативное решение, когда подсказка выводится с помощью элемента <label>. Каждую строку заключим в <div> с классом row, а внутрь вставим <input> и <label>, связав их друг с другом через атрибуты id и for.

<div class="row">
  <input type="text" name="login" id="login">
  <label for="login">Логин</label>
</div>

Стиль для <input> останется тем же, что и в примере 1, и добавится только стиль для <label>. Чтобы текст подсказки отображался поверх поля формы превращаем <label> в блочный элемент и смещаем его вверх через свойство transform с функцией translateY. Так же важно задать постоянный line-height, поскольку шрифт при фокусе будет уменьшаться, соответственно, уменьшаться и межстрочное расстояние, что приведёт к «скачкам» текста. Здесь же ставим и время трансформации подсказки.

.row label {
  display: block; /* Блочный элемент */
  color: #aaa; /* Цвет подсказки */
  transform: translateY(-1.5rem); /* Сдвигаем вверх */
  line-height: 1rem; /* Межстрочный интервал */
  transition: 0.5s; /* Время трансформации */ 
}

Для определения стиля подсказки при получении фокуса используем селектор input:focus+label. Но этого недостаточно, ведь если набрать в поле текст и убрать фокус, подсказка вернётся в своё исходное положение и будет отображаться поверх введённого текста. Нам надо сделать так, что если в поле содержится текст, то подсказка остаётся вверху. Для этого подключаем селектор input:valid+label, он задаёт стиль <label>, когда в <input> введён корректный текст.

.row input:focus + label, 
.row input:valid + label { 
  font-size: 10px; /* Размер шрифта */
  transform: translateY(-2.5rem); /* Сдвигаем вверх */
}

Псевдокласс :valid работает для полей формы, когда в них вставлен атрибут required. Так что в коде HTML добавляем этот атрибут к <input>, как показано в примере 2.

Пример 2. Подсказка через <label>

<!DOCTYPE html>
<html>
<head>
<meta charset=»utf-8″>
<title>:focus</title>
<style>
form {
background: #f5f5f5; /* Цвет фона */
width: 300px; /* Ширина формы */
margin: auto; /* Выравниваем по центру */
padding: 20px; /* Поля вокруг текста */
}
.row input {
width: 100%; /* Ширина поля */
box-sizing: border-box; /* Ширина не учитывает padding */
padding: 0.5rem 0; /* Поля вокруг текста */
border: none; /* Убираем рамку */
border-bottom: 1px solid #ccc; /* Линия снизу */
background: transparent; /* Прозрачный фон */
}
.row input:focus {
outline: none; /* Убираем контур */
border-color: #1976D2; /* Синяя линия снизу */
}
.row label {
display: block; /* Блочный элемент */
color: #aaa; /* Цвет подсказки */
transform: translateY(-1.5rem); /* Сдвигаем вверх */
line-height: 1rem; /* Межстрочный интервал */
transition: 0.5s; /* Время трансформации */
}
.row input:focus + label,
.row input:valid + label {
font-size: 10px; /* Размер шрифта */
transform: translateY(-2.5rem); /* Сдвигаем вверх */
}
</style>
</head>
<body>
<form action=»/example/handler.php»>
<div class=»row»>
<input type=»text» name=»login» id=»login» required>
<label for=»login»>Логин</label>
</div>
<div class=»row»>
<input type=»password» name=»pass» id=»pass» required>
<label for=»pass»>Пароль</label>
</div>
</form>
</body>
</html>

См. также

Последнее изменение: 11.03.2020

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Как изменить цвет label html
  • Как изменить цвет jframe java
  • Как изменить цвет input type radio
  • Как изменить цвет input range css
  • Как изменить цвет imgui lua

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии