Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery: Click a random link on document ready

I have five links on a page which display different content on another part of the page when clicked. Each link has an ID and I have a simple click function on document ready to select the first link:

$('#link1').click();

How can I have it click one of the five links at random on document ready, instead of #link1 specifically? And yes, I realize that a click function probably isn't the ideal way to handle this.

Thanks in advance!

like image 525
fast Avatar asked Dec 08 '25 02:12

fast


2 Answers

The smoov jQuery way of doing things:

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

<script type="text/javascript">
 $().ready(function() {
     alert($("a:random").click());
 }); 
 </script>

(I knew about custom selectors, but still shamelessly stolen from here)

Slightly less smoov:

$(function() {
   var links = $('a');
   var randomNum = Math.floor(Math.random()*links.length)  
   links.get(randomNumber).click();
} 

If you want links with an ID that start with link, you can always do:

   var links = $("a[id^='link']");

And now it doesn't matter whether you use numbers or whatever. Anything that has an ID that starts with link. (naturally, you could apply it to a particular css class too)

like image 98
cgp Avatar answered Dec 10 '25 16:12

cgp


something like this?

var randomnumber=Math.floor(Math.random()*5)
$($('a').get(randomnumber)).click();
like image 39
John Boker Avatar answered Dec 10 '25 14:12

John Boker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!