How to Select a Random Element in jQuery

How to Select a Random Element in jQuery
In jQuery adds its own selection filters. As with everything else in the library, you can also create your own. To do this simply add a new function to the $.expr[':'] object. You can see a slightly modified version of his code below:


(function($){
    var random = 0;

    $.expr[':'].random = function(a, i, m, r) {
        if (i == 0) {
            random = Math.floor(Math.random() * r.length);
        }
        return i == random;
    };

})(jQuery);

// This is how you use it:
$('li:random').addClass('glow');
Ashwani
Ashwani

This is a short biography of the post author. Maecenas nec odio et ante tincidunt tempus donec vitae sapien ut libero venenatis faucibus nullam quis ante maecenas nec odio et ante tincidunt tempus donec.

No comments:

Post a Comment