Monday, 9 April 2018

Adding class randomly to HTML elements with jQuery

HTML

<div id="menu">
<ul>
    <li>Autos</li>
    <li>Real Estate</li>
    <li>Services</li>
    <li>Boats</li>
    <li>Gardening</li>
</ul>
</div>
 
<script>
$(document).ready(function(){
// create random number
  function randOrder() {
    return ( Math.round(Math.random())-0.5 ); 
  } 
 
$(document).ready(function() {
 
    // classses array
    var classes = [ 'li-one', 'li-two', 'li-three', 'li-four', 'li-five' ];
    // sort array elements randomly
    classes.sort( randOrder );
 
    // uncomment below to see order
    // alert( classes.sort( randOrd ) );
 
    // create loop to add each array element as a class
    $('#menu ul li').each(function(i, val) {
        $(this).addClass(classes[i]);
    });
});
});
</script> 

No comments:

Post a Comment