• Welcome to TechPowerUp Forums, Guest! Please check out our forum guidelines for info related to our community.

Displaying a random element between 4 choices

Joined
Dec 27, 2008
Messages
587 (0.10/day)
System Name PC
Processor i5 2500k
Motherboard P8Z68-V PRO/GEN3
Cooling Fans
Memory DDR3-1600 (8GB)
Video Card(s) Sapphire Nitro+ RX 580
Storage HD103SJ
Display(s) XG2402
Case Xigmatek Midgard II
Power Supply PC Power & Cooling Silencer 750W
Hi all.

I have four <div> elements and I'm trying to use Javascript to display one of the four (the rest would be hidden).

I have the HTML/CSS in place, it's the Javascript that's giving me trouble.

<div id="numberOne">
<div id="numberTwo">
<div id="numberThree">
<div id="numberFour">

I need the Javascript that will randomly select one of these divs and display it.

This is what I have so far. I could be way off.

Code:
<script>
var array = [];
var selectedValue = Math.floor(Math.random() * array.length);
var selectedDiv = document.getElementById(selectedValue);
selectedDiv.style.display = "block";
</script>
 

ntgamers

New Member
Joined
Apr 6, 2015
Messages
6 (0.00/day)
You're on the right track but your array isn't populated in your code sample, you need to place "numberOne","numberTwo" etc. into your array and i'm pretty sure your stuff will work, but you should also make sure they have a default style of display: none first
 
Joined
Dec 27, 2008
Messages
587 (0.10/day)
System Name PC
Processor i5 2500k
Motherboard P8Z68-V PRO/GEN3
Cooling Fans
Memory DDR3-1600 (8GB)
Video Card(s) Sapphire Nitro+ RX 580
Storage HD103SJ
Display(s) XG2402
Case Xigmatek Midgard II
Power Supply PC Power & Cooling Silencer 750W
Thanks for the reply, ntgamers.

When I wrote this yesterday I was in a bit of a rush and I see I left some things out (I do have display: none applied to the divs), but this is the point I'm at currently.

Code:
var first = document.getElementById("first_div").innerHTML;
var second = document.getElementById("second_div").innerHTML;
var third = document.getElementById("third_div").innerHTML;
var fourth = document.getElementById("fourth_div").innerHTML;

var thisArray = [first, second, third, fourth];
var selectedValue = Math.floor(Math.random() * thisArray.length);
var selectedDiv = document.getElementById(selectedValue);
document.getElementById("show").innerHTML = selectedDiv;

I added a div without any style that will be populated with one of the four selected divs. You'll notice I removed the
Code:
selectedDiv.style.display = "block";
I wasn't getting this to work as well as just putting everything inside <div id="show">.

If I change
Code:
document.getElementById("show").innerHTML = selectedDiv;
to
Code:
document.getElementById("show").innerHTML = selectedValue;
I see the number 0-3, which I expect.

The problem is I just can't get the content of a random div to show!
 

ntgamers

New Member
Joined
Apr 6, 2015
Messages
6 (0.00/day)
var fourth = document.getElementById("fourth_div").innerHTML;

Why are you getting the innerHTML of the element instead of the element itself? In this case I see you trying to get the innerHTML and then you are searching for the element based on the innerHTML of that element.


var selectedDiv = document.getElementById(selectedValue);

In that case selectedValue is already the innerHTML so you would not get the selectedDiv populated because it won't find the element as it's looking for "fourth_div" not what fourth_div contains.


var thisArray = ['first_div', 'second_div', 'third_div', 'fourth_div'];

Try only referencing the id's in your array, you do not need to fetch the elements until you have one selected


var selectedDiv = document.getElementById(selectedValue);

Should now function and you should be good to go.
 
Joined
Dec 27, 2008
Messages
587 (0.10/day)
System Name PC
Processor i5 2500k
Motherboard P8Z68-V PRO/GEN3
Cooling Fans
Memory DDR3-1600 (8GB)
Video Card(s) Sapphire Nitro+ RX 580
Storage HD103SJ
Display(s) XG2402
Case Xigmatek Midgard II
Power Supply PC Power & Cooling Silencer 750W
Hey man, sorry I'm getting back to you late. I read your response shortly after you posted it, but I'm having trouble with some of the stuff you're saying. I'll try and go piece-by-piece, like you did.

You're saying I'm still okay to (excuse my verbage if I'm wrong here) store that method as a variable, but by getting the element itself, I'm already getting the content of that element?

I'm not sure what you mean by "then you are searching for the element based on the innerHTML of that element". The way I understood this part of the code
Code:
var selectedValue = Math.floor(Math.random() * thisArray.length);
var selectedDiv = document.getElementById(selectedValue);
is that I'm storing the random selection of one of the array items [0-3], then storing the method to get that selected item and displaying it.
 

ntgamers

New Member
Joined
Apr 6, 2015
Messages
6 (0.00/day)
The way I understood this part of the code


var first = document.getElementById("first_div").innerHTML;
var second = document.getElementById("second_div").innerHTML;
var third = document.getElementById("third_div").innerHTML;
var fourth = document.getElementById("fourth_div").innerHTML;

Right, that section of the code looks correct. However your array items are the inside of the elements themselves, whereas you only need the id's of each inside your array not the elements themselves as you are getting the element based on it's ID

var selectedDiv = document.getElementById(selectedValue);
 
Joined
Dec 27, 2008
Messages
587 (0.10/day)
System Name PC
Processor i5 2500k
Motherboard P8Z68-V PRO/GEN3
Cooling Fans
Memory DDR3-1600 (8GB)
Video Card(s) Sapphire Nitro+ RX 580
Storage HD103SJ
Display(s) XG2402
Case Xigmatek Midgard II
Power Supply PC Power & Cooling Silencer 750W
var first = document.getElementById("first_div").innerHTML;
var second = document.getElementById("second_div").innerHTML;
var third = document.getElementById("third_div").innerHTML;
var fourth = document.getElementById("fourth_div").innerHTML;

Right, that section of the code looks correct. However your array items are the inside of the elements themselves, whereas you only need the id's of each inside your array not the elements themselves as you are getting the element based on it's ID

var selectedDiv = document.getElementById(selectedValue);

When you quote my post, but then you include more code followed by "Right, that section of the code looks correct", I don't know if you're referring to just what I said or what you added or both.

I understand that each variable stores the innerHTML (content) of the div it gets. My array items are those variables and in turn are the inside of the elements, which is what you seem to be saying. If I only need the IDs inside my array, then you are saying I can drop the section of code where I declare variables: first, second, third, fourth?

The resulting code would be:

Code:
var thisArray = ["first_div", "second_div", "third_div", "fourth_div"];
var selectedValue = Math.floor(Math.random() * thisArray.length);
var selectedDiv = document.getElementById(selectedValue);
selectedDiv.style.display = "block";

This seems logical enough. The random math is done and a value selected, then I get that ElementById as a function of the selectedValue. However, this doesn't work for some reason.
 
Joined
Nov 22, 2007
Messages
1,398 (0.23/day)
Location
Hyderabad,India
System Name MSI apache ge62 2qd
Processor intel i7 5700HQ
Memory 12 Gb
Video Card(s) GTX960m
Storage 1TB
Display(s) Dell 24'
Try a switch case

switch(rand())
case 1: element 1
break;
case 2: element 2
break;
.
.
.
.
.
 

FordGT90Concept

"I go fast!1!11!1!"
Joined
Oct 13, 2008
Messages
26,259 (4.63/day)
Location
IA, USA
System Name BY-2021
Processor AMD Ryzen 7 5800X (65w eco profile)
Motherboard MSI B550 Gaming Plus
Cooling Scythe Mugen (rev 5)
Memory 2 x Kingston HyperX DDR4-3200 32 GiB
Video Card(s) AMD Radeon RX 7900 XT
Storage Samsung 980 Pro, Seagate Exos X20 TB 7200 RPM
Display(s) Nixeus NX-EDG274K (3840x2160@144 DP) + Samsung SyncMaster 906BW (1440x900@60 HDMI-DVI)
Case Coolermaster HAF 932 w/ USB 3.0 5.25" bay + USB 3.2 (A+C) 3.5" bay
Audio Device(s) Realtek ALC1150, Micca OriGen+
Power Supply Enermax Platimax 850w
Mouse Nixeus REVEL-X
Keyboard Tesoro Excalibur
Software Windows 10 Home 64-bit
Benchmark Scores Faster than the tortoise; slower than the hare.
You could save yourself a lot of time by changing the ids to "random#" where # is replaced with a numeric value. All you have to do to select it then is append the number to the name. It completely automates the programming side of it.

Additionally, make sure all of these divisions have its visibility property set to "none." I believe you can do this via CSS class--ID "block" should override the class value of "none."


There's examples here of how to find all instances of an ID that begins with something (e.g. "random"). The logic of it:
1. Add a class to all divs that set their visibility to none (e.g. class="hidden" defined in CSS).
2. Change the IDs to use numeric instead of spelled out (e.g. id="random0" id="random1" id="random2" id="random3" and so on)
3. Use the Math.floor code you already have to get a random index from elements whose ID starts with "random"
4. Get the specific element ID by appending "random" to the index.
5. If element ID is found, make it visible.


Code:
var thisArray = ["first_div", "second_div", "third_div", "fourth_div"];
var selectedValue = Math.floor(Math.random() * thisArray.length);
var selectedDiv = document.getElementById(selectedValue);
selectedDiv.style.display = "block";
selectedValue = integer (result from Math.floor)

Unless there is an element with an ID of "0" "1" "2" and so on, that won't find it. selectedDiv is effectively always null. To rectify this, I believe all you need to do is thisArray[selectedValue].
 
Last edited:
Top