To select an image at random from imageTabList
, you can do this:
var randomImg = imageTabList[Math.floor(Math.random() * imageTabList.length)];
To get a random longDesc
attribute each time you load the page, you can use this code:
var imgs = document.getElementById("imageTabs").document.getElementsByTagName("img");
var randomImg = imgs[Math.floor(Math.random() * imgs.length)]
var randomLong = randomImg.getAttribute("longdesc");
FYI, you should be using data-longdesc="xxxx"
at the attribute for HTML5 compatibility.
Here's an explanation:
Math.random()
creates a random floating point number between 0
and 1
(including 0
, not including 1
) such as 0.4857462391
.
Math.random() * imageTabList.length
creates a random floating point number between 0
and imageTabList.length
(including 0
, not including imageTabList.length
such as 8.239824379
.
To make that value an integer (for an array index), we call Math.floor()
on it as in:
Math.floor(Math.random() * imageTabList.length)
Now you have a random integer between 0 and imageTablList.length - 1 that you can use to grab a random item from that NodeList.
If you need any further help, please show your HTML as it isn't quite clear from your code what you're trying to do.