Javascript – Make background color change on hover after setting style using ng-style

angularjsjavascript

I have a list of words with a number (streak) assigned to each word. I set the background color of each word based on the number assigned to it using AngularJS's ng-style.

html

   <ul class="unstyled">
     <li class="tHi" ng-repeat="item in items" ng-click="getEdit(item.word)" ng-style="bgstyle(item.streak)">
       <span>{{item.word}} {{item.streak}}</span>
     </li>
   </ul>

javascript that is called from ng-style.

$scope.bgstyle = function (streak) {
    var red = 255;
    var green = 255-streak;
    var blue = 255-streak;
    var rgb = blue | (green << 8) | (red << 16);
    var sColor = '#' + rgb.toString(16);
    return {backgroundColor: sColor};
}

This works, however, I would like the background to be highlighted when the mouse hovers over a word. I added a class "tHi" that normally would change the background on hover, but it is overridden by the added style.

Here is a jsfiddle that demonstrates this issue.

Is there a better way to set the background than ng-style so that it corresponds to the number assigned to each word? Or is there a way to highlight when a user hovers over a word?

Best Answer

This is one of the very few cases where I'd actually suggest using !important in CSS:

.tHi:hover {
    cursor: pointer;
    background-color: #9f9 !important;
}

Updated JS Fiddle demo.

Using the !important keyword essentially causes the rule to be applied regardless of the specificity of the selector (assuming that a more-specific selector doesn't also have the !important keyword, of course). It does, however, have the potential to make debugging quite difficult, if you, or your colleagues, forget about the use of the !important.

References: