JQuery: click any link to the finished document.

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

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

How can I click one of the five links in random order on the finished document, and not on # link1? And yes, I understand that the click function is probably not the perfect way to handle this.

Thanks in advance!

+3
source share
5 answers

Smoov jQuery method:

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 smaller smoov:

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

, , :

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

, - . , , . (, css)

+7

- ?

var randomnumber=Math.floor(Math.random()*5)
$($('a').get(randomnumber)).click();
+2

Assuming the links of interest begin with a “link” followed by a number:

$('a[id="link' + Math.floor(Math.random() * 5) + '"]')[0].click();
+1
source

I think it will be

links = new Array();
$('a').each(function() { links.push($(this)) });
el = links[Math.floor(Math.random()*links.length)]
el.click();

This grabs all the links on the page and puts them in an array, and then clicks on one of them.

0
source

Another possible hack:

$('a[href^="link"]').sort(function(){return Math.random()-0.5}).eq(0).click()

The above code shuffles the links and returns the first. Then you can call the 'click' of the returned item

0
source

All Articles