I'm at a complete loss as to how to get my code working correctly. I've looked at so many other forums and questions, but have yet to get it functioning. As the title suggests, it always goes with the second if statement no matter what. What I'm trying to do is get a random variable (either 1 or 2) and use that to decide which of two divs with the same class to display. I have them defaulting to display:none and having the variable change them to display: block because the divs are shown based on geolocation and if there are two instead of one, I only want one to show but be randomly picked. Here's the code I'm trying to get working:
window.onload = function() {
function randomNumber(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var randintvar=randomNumber(1,2);
if (randintvar == 1) {
document.querySelector(".variable-div").style.display = "none";
document.querySelector(".variable-div:first-child").style.display = "block";
}
if (randintvar == 2) {
document.querySelector(".variable-div").style.display = "none";
document.querySelector(".variable-div:last-child").style.display = "block";
}
}
<div class="variable-div">
First Div
</div>
<div class="variable-div">
Second Div
</div>
I did get this to work properly:
window.onload = function() {
function randomNumber(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var randintvar=randomNumber(1,2);
alert(randintvar);
}
That ended up working to show an alert and is able to randomly show one of two integers, so it has something to do with my "if" statements. I've been banging my head trying to figure it out. Help save me please!
Appreciate any input. Thank you!