1

I followed this tutorial http://code.stephenmorley.org/html-and-css/star-rating-widget/ to build a star rating HTML/CSS component.

Now I want to modify it that the stars can't change when someone hovers over it. So I thought I add a class disabled to every label and then I adapt the CSS like this:

.starRating:not(old) > label:not(.disabled):hover:before,
.starRating:not(old) > label:not(.disabled):hover ~ label:not(.disabled):before,
.starRating:not(:hover) > :checked ~ label:before{
   opacity : 1;
}

But still when my mouse comes over the stars it keeps doing the changes.

HTML:

<span class="starRating">
    <input id="rating5" type="radio" name="rating" value="5" disabled checked>
    <label class="disabled" for="rating5">5</label>
    <input id="rating4" type="radio" name="rating" value="4" disabled>
    <label class="disabled" for="rating4">4</label>
    <input id="rating3" type="radio" name="rating" value="3">
    <label class="disabled" for="rating3">3</label>
    <input id="rating2" type="radio" name="rating" value="2">
    <label class="disabled" for="rating2">2</label>
    <input id="rating1" type="radio" name="rating" value="1">
    <label class="disabled" for="rating1">1</label>
</span>
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
user1007522
  • 7,858
  • 17
  • 69
  • 113

2 Answers2

0

Found the solution. You need to add a new line that specifies what happens when it is disabled.

.starRating:not(.disabled):not(:hover) > :checked ~ label:before,
.starRating:not(.disabled):not(old) > label:hover:before,
.starRating:not(.disabled):not(old) > label:hover ~ label:before,
.starRating.disabled > :checked ~ label:before {
  opacity : 1;
}
user1007522
  • 7,858
  • 17
  • 69
  • 113
0

This can be done easily without adding any additional classes:

.starRating:not(old) > input:not([disabled])+label:hover:before,
.starRating:not(old) > input:not([disabled])+label:hover ~ label:before,
.starRating:not(:hover) > :checked ~ label:before,
.starRating:not(old) > :checked[disabled] ~ label:before{
  opacity : 1;
}

The way this works is that first you change all of the existing selectors to reflect the fact that they shouldn't be after a disabled input. This means that once you disable all the inputs the stars will not show.

However, this causes the checked stars to not show either. To fix this you add a fourth selector that selects the pseudo element for every label after a checked but disabled input. This means that now when disabled, hovering will not do anything and, when not disabled, the behaviour remains the same as before.

This means you can disable the input by just adding the disabled attribute to every input rather than adding both the attribute and a class to the labels.

Kaamil Jasani
  • 464
  • 5
  • 11