4

I have a static page that shows a value in a list. This value represents the percentage of a project that was spent on each individual practice. Is there a way to display a background image in the li based on the value of the content? I'm sure there is a javascript fix for this but I'm not sure where to start. Javascript is not my strong point at all.

There will be 4 values used (25 / 50 / 75 / 100) and a different image will be displayed depending on the value in the li.

The HTML is:

<div class="col-md-6">
  <ul class="list-inline stats">
    <li>25<small>Strategy</small></li>
    <li>25<small>Design</small></li>
    <li>25<small>Production</small></li>
    <li>25<small>Marketing</small></li>
  </ul>
</div>

Any help would be appreciated. Thank you in advance.

Dhanu Gurung
  • 8,480
  • 10
  • 47
  • 60
Stephen Smith
  • 89
  • 2
  • 6

5 Answers5

6

You can add classes to the elements using JavaScript based on the numbers:

$('.list-inline li').addClass(function() {
   return 'bg' + this.firstChild.nodeValue;
});

Then in your css declare the classes:

.bg25 { background-image: ... }    
.bg50 { background-image: ... }

http://jsfiddle.net/xcJ47/

You can also define a JavaScript object and use the jQuery .css() method:

var bgs = {
   '25' : 'url(...)',
   '50' : 'url(...)',
   '75' : 'url(...)',
   '100': 'url(...)'
   // ...
}

$('.list-inline li').css('background-image', function() {
    return bgs[this.firstChild.nodeValue];
});
Ram
  • 143,282
  • 16
  • 168
  • 197
0

Could you not make something like this?

HTML

<li class="percentage_li" data-percent="25">25<small>Strategy</small></li>

jQuery

var curr_percent = 0;

$(".percentage_li").each(function(){
    curr_percent = $(this).data('percent');
    $(this).css({'background-image':'url('images/'+curr_percent+'.jpg')'});
});
display-name-is-missing
  • 4,424
  • 5
  • 28
  • 41
0

this is static page. right? then add style in each li based on the value. like

<li style="background-image:url('first.gif');">
<li style="background-image:url('second.gif');">
<li style="background-image:url('third.gif');">
<li style="background-image:url('fourth.gif');">
DixonMD
  • 93
  • 1
  • 11
0

you cann add a class to the li like this and have your image set in css

$(document).ready(function(){
    var $elem = $('.list-inline li');
    var strClass = $elem.html().substr(0,2);
    $elem.addClass(strClass);
});

if there is no class name given you might have to add some string cause its no good to have a class name starting with digits soo the last line should look somthing like

        $elem.addClass('myNewStyle '+strClass);
caramba
  • 21,963
  • 19
  • 86
  • 127
0

You can use jQuery's :contains(). For example (fiddle)

$('.list-inline.stats li:contains(25)').css({background: 'red'})
$('.list-inline.stats li:contains(50)').css({background: 'green'})
$('.list-inline.stats li:contains(75)').css({background: 'blue'})
kmakarychev
  • 731
  • 4
  • 14