Friday, September 21, 2012

Randomly sort and display a set of elements using jQuery

I ran into a situation where I needed to randomly select a set of hidden elements from a web page and display only those elements. I also wanted to randomize the order of those elements so the page looked different each time. Here is a quick jQuery example.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var root = $('#tips');
            var tips = $('div.singleTip:hidden');
            $(tips).detach();
            var count = 0;
            var maxCount = 2;
            while (count <= maxCount) {
                var idx = Math.floor(Math.random() * tips.length);
                if ($(tips[idx]).is(':hidden')) {
                    $(tips[idx]).show();
                    root.append($(tips[idx]));
                    ++count;
                }
            }
        });
    </script>
    <style type="text/css">
        .singleTip {
            display: none;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div id="tips">
            <div class="singleTip">one</div>
            <div class="singleTip">two</div>
            <div class="singleTip">three</div>
            <div class="singleTip">four</div>
            <div class="singleTip">five</div>
            <div class="singleTip">six</div>
            <div class="singleTip">seven</div>
        </div>
    </form>
</body>
</html>

No comments:

Can't RDP? How to enable / disable virtual machine firewall for Azure VM

Oh no!  I accidentally blocked the RDP port on an Azure virtual machine which resulted in not being able to log into the VM anymore.  I did ...