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!
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)
something like this?
var randomnumber=Math.floor(Math.random()*5)
$($('a').get(randomnumber)).click();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With