Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 984
Daniel Avatar asked Dec 31 '12 20:12

Daniel


People also ask

How do I change the background color in style?

To set the background color in HTML, use the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <body> tag, with the CSS property background-color. HTML5 do not support the <body> tag bgcolor attribute, so the CSS style is used to add background color.

How do I change the background color in style tag?

How to Add Background Color in HTML. To add background color in HTML, use the CSS background-color property. Set it to the color name or code you want and place it inside a style attribute. Then add this style attribute to an HTML element, like a table, heading, div, or span tag.

How do you hover in NgStyle?

if you want to switch styles on hover, add the following to the button <button (mouseover)="hover=true" (mouseleave)="hover=false" ...


1 Answers

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:

  • !important.
like image 114
David Thomas Avatar answered Sep 19 '22 19:09

David Thomas