VIEW ALL GALLERY LIGHTS

Monday, July 19, 2010

Adding counter to sequential list using Jquery

In my design work ,I have to create sequential lists ,for example ,a list of blog comments ,lists of users ... adding counter to these lists will make it look better but sometime it's hard to do manually . I find out a solution from webdesignerwall.com ,using jquery to add numbers to the list .





Live Demo 
Here is detail instruction :
1,First,we need CSS code to decorating numbers 
/* number style */
#commentlist {
margin: 10px 0 40px;
padding: 0;
}
#commentlist li {
padding: 10px 0 20px;
list-style: none;
border-top: solid 1px #ccc;
position: relative;
}
#commentlist cite {
font: bold 140%/110% Arial, Helvetica, sans-serif;
color: #666;
}
#commentlist .time {
color: #ccc;
margin: 0 0 10px;
}
#commentlist .commentnumber {
position: absolute;
right: 0;
top: 8px;
font: normal 200%/100% Georgia, "Times New Roman", Times, serif;
color: #ccc;
2,Add this Jquery code anywhere in template or HTML file :
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){

  $("#commentlist li").each(function (i) {
    i = i+1;
    $(this).prepend('<span class="commentnumber"> #' i '</span>');
   });

});
</script>
This code will find all <li> elements covered under element which has  id="commentlist" , and insert <span class="commentnumber"> #' i '</span> into each <li>.......</li>
so we get the result after adding code:
here is original HTML code 
<ol id="commentlist">

    <li>
        ............
    </li>
    <li>
        ...................
    </li>
    <li>
        .................
    </li>
</ol>
and here is the code after adding numbers
<ol id="commentlist">

    <li>
<span class="commentnumber"> #1</span>
        ............
    </li>
    <li>
<span class="commentnumber"> #2</span>
        ...................
    </li>
    <li>
<span class="commentnumber"> #3</span>
        .................
    </li>
................
</ol>
That's all . Thanks for reading and I hope you find it useful

No comments:

Post a Comment