Jquery Changing CSS class of object based on numeric content

Going to be outputting percentages dynamically 0-100%

Want to add CSS class based on percentage. Red for 0% and Blue for 100% progressively.

Markup would be

<span class="blue">100%</span>

Originally I had thought something along this line....

$("span:contains('100%')").css("color", "#0000ff");

But contains only searching first integer and applying different classes for 1,2,3,4,5,6,7,8,9 only problem with this method is single digit numbers would be treated the same as double. IE 7% and 70% would have the same class and wouldn't be correct.

These aren't specific amounts, they are going to dynamically change all the time. I am not very good at writing my own jquery so any help is appreciated.

Answers:

Answer

DEMO: http://jsfiddle.net/JAAulde/GJh3j/

Contains is going to be a pretty expensive query if you have a lot of elements on the page. I would:

Add a class to all elements:

<span class="percent-holder">100%</span>
<span class="percent-holder">100%</span>
<span class="percent-holder">0%</span>
<span class="percent-holder">100%</span>

Find all those elements, analyze their text, do what you want:

$( '.percent-holder' ).each( function()
{
    var $this = $( this ),
        classToAdd = null;

    switch( $this.text() )
    {
        case '100%':
            classToAdd = 'blue';
            break;

        case '0%':
            classToAdd = 'red';
            break;
    }

    if( classToAdd !== null )
    {
        $this.addClass( classToAdd );
    }
} );
Answer

I see nothing wrong with using :contains() (see http://jsfiddle.net/b3tUf/), but if you want to change your code, you could always just use conditional statements.

if( $("span").text() == "0%" ) {
    $("span").css("color", "#0000ff");
} elseif ( $("span").text() == "100%" ) {
    ...
}

or for classes:

if( $("span").text() == "0%" ) {
    $("span").removeClass().addClass("red");
} elseif ( $("span").text() == "100%" ) {
    $("span").removeClass().addClass("blue");
}
Answer

If you wanna manage the percentage colors yourself manually, you could do it like this:

$('span').css('color', function() {
 var percentage = parseInt($(this).text());  
    switch(percentage){
        case 100:
          return "red";
        case 90:
          return "gray";                 
    }
});

example: http://jsfiddle.net/niklasvh/zqwqe/

edit: alternatively you could calculate the color value dynamically, so you wouldn't have to define each percentage seperately.

    $('<span />').appendTo($('body')).text(i+"%").css('color', function() {
        var percentage = parseInt($(this).text());  
        var colors = [Math.round(255*(percentage/100)),0,255-Math.round(255*(percentage/100))];
        return "rgb("+colors+")";   
        });

example: http://jsfiddle.net/niklasvh/zqwqe/29/

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.