jQuery HTML Element How to - Randomly choose a hyperlink








Question

We would like to know how to randomly choose a hyperlink.

Answer


<html>
<head>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script>
        $(document).ready(function(){<!--from  ww  w  .j a  va2  s. c  om-->
            myLinks = new Array;
            myLinks[0] = "#one";
            myLinks[1] = "#two";
            myLinks[2] = "#three";

            // Slide to random link
            $("a.myRandomLink").click(function(){
                randomLink = Math.round(Math.random() * (myLinks.length-1));
                $("html, body").animate({scrollTop: $(myLinks[randomLink]).offset().top + "px"},{duration: 500, easing: "swing"});
                return false;
            });
        });
    </script>
</head>
<body>

    <a href="#" class="myRandomLink">Random link</a><br><br>

    <div id="one" style="width:100%;height:600px;background-color:#550000;"></div>
    <div id="two" style="width:100%;height:600px;background-color:#005500;"></div>
    <div id="three" style="width:100%;height:600px;background-color:#000055;"></div>
    <div id="four" style="width:100%;height:600px;background-color:#ffffff;"></div>

</body>
</html>

The code above is rendered as follows: