Jquery/Javascript Display one of two items randomly on each access

Asked

Viewed 25 times

0

Good morning friends! All right?

My case is this: I have two cell phone numbers, and I want each access, I display a different number. I tried to do something with Math.Run between 2 and 1, with a conditional deviation of if it is 1 I display number one and if it is 2 I display number two Follow the model below:

$(document).ready(function(){
                let x = Math.floor((Math.random() * 2) + 1);
                if( x == 1) {
                    $('#number').text('numero um');
                } else {
                    $('#number').text('numero dois');
                }
            });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<p id="number"></p>

In my head it would be 50% for each number, but I discovered that randomly it can repeat the number.

My question is: is there any way to work with a different number for each access without repeating (client side) or should I look for some solution on the server side?

Still thinking about client side, I was thinking about doing something with cookie to try to display each number without repeating.

1 answer

1


If your idea is that the same person sees randomly, the solution that comes to mind is the cookie or location Torage, so you keep key with the number 1 on the first access and put a logic

var num = 1;//'O VALOR DO SEU COOKIE OU LOCAL STORAGE';
if(num == 1){
  console.log('exibe numero dois');
}else{
  console.log('exibe numero um');
  //altera o valor do cookie/ local storage aqui   
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.