Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Randomly chosen class to HTML tag using jQuery

Whet I need to do is in my menu I would like to add one of the classes (listed below) with completely random order every time when function starts (page load)

This is my HTML

<div id="menu">
    <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">About Us</a></li>
        <li><a href="#">Portfolio</a></li>
        <li><a href="#">Why Us</a></li>
        <li><a href="#">Contact Us</a></li>
    </ul>
</div>

And this is what I would like to have as the result with every time different order of added classes

<div id="menu">
    <ul>
        <li><a href="#" class="li-one" >Home</a></li>
        <li><a href="#" class="li-five">About Us</a></li>
        <li><a href="#" class="li-three">Portfolio</a></li>
        <li><a href="#" class="li-two">Why Us</a></li>
        <li><a href="#" class="li-four">Contact Us</a></li>
    </ul>
 </div>

Below I have listed all the classes.

.li-one .li-two .li-three .li-four .li-five

I have spent lost hour trying to figure that out with no results

Thank you very much for your help in advance

like image 389
Dom Avatar asked Dec 16 '09 02:12

Dom


Video Answer


1 Answers

Something like the following:

function randOrd() {
    return (Math.round(Math.random())-0.5); 
}

$(document).ready(function() {
    var klasses = [ 'li-one', 'li-two', 'li-three', 'li-four', 'li-five' ];
    klasses.sort( randOrd );
    $('#menu ul li a').each(function(i, val) {
        $(this).addClass(klasses[i]);
    });
});
like image 145
karim79 Avatar answered Oct 01 '22 08:10

karim79