Wasim Shaikh
Wasim Shaikh

Reputation: 7030

How to add random class to link list

I have following structure.

<ul id="dyn_nav">
    <li><a href="#">Home</a></li>
    <li><a href="#">Services</a></li>
    <li><a href="#">Contact</a>
        <ul class="submenu">
            <li><a href="#">Home</a></li>
            <li><a href="#">Services</a></li>
            <li><a href="#">Contact</a></li>
        </ul>
    </li>
</ul>

The first level of li (ul#dyn_nav>li) should get random classes from given list.

Classes are blue, green, magenta, cyan, red, etc...

I want to make this menu dynamic color not fixed.

Like one can have first menu color green, another have blue. This is just my Idea.

jQuery please.

Upvotes: 1

Views: 2238

Answers (3)

David Conrad
David Conrad

Reputation: 16359

$(document).ready(function() {
    var classes = ['blue', 'green', 'magenta', 'cyan', 'red'];
    $('ul#dyn_nav>li').each(function(i) {
        $(this).addClass(
            classes[Math.floor(Math.random()*classes.length)]);
    });
});

I also added ul#dyn_nav>li>a { color: inherit; } to the stylesheet so that the color would affect the link in the li and not just the bullet.

Upvotes: 7

thecodeparadox
thecodeparadox

Reputation: 87073

Dutow is right. @Wazdesign: You can also try this snippet:

function rand(){ return (Math.round(Math.random())-0.5); }
    var colors = new Array('blue','yellow','red','green');//you can add more class here
    var init = colors.sort( rand );
    $('ul li').each(function(i,el){ 
     $(el).addClass(init[i]); 
   });

Upvotes: 0

Dutow
Dutow

Reputation: 5668

Put your colors into an array, randomize it, and use jQuery.each with addClass to assign the values.

Upvotes: 1

Related Questions