Search code examples
jqueryhyperlinkhref

Randomly choose a hyperlink


On my blog I have 12 different genres (Music, Photography, Architecture etc...) and then at least 2 different images of each genre on one page. I am currently using smoothscroll.js. When you click on photography (for example) it will currently go straight to the first Hyperlink(X)

<a href="#photgraphy"> photography </a>




<a name="photography"> </a> [X]
<a name="photography"> </a> [Y]

Is there a way that when you click on photography it chooses randomly X or Y instead of it going to the first hyperlink (X).


Solution

  • <html>
    <head>
        <script src="http://code.jquery.com/jquery-latest.min.js"></script>
        <script>
            $(document).ready(function(){
                // Create an array of links
                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>