Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

161
Visualizações
How do I save a randomized result (which will be different with every reload) on my webpage with local storage?

I have made a website where you can generate a random workout, that is, a workout with 5 random exercises combined with 5 random types of reps. To generate a random amount of reps I used Math.floor(Math.random() to the array I made. To generate 5 different, random workouts I used the shuffle function in Javascript to shuffle my array every time the page reloads.

Now I want the user to be able to save whatever result they got up on their webpage to the local storage on their computer so they can access that specific randomized workout whenever they want. How do I go about this???

Down here I publish the code I created to generate the result.

// This makes the reps generate randomly in a list of 5

let maxNr = 10;

function generateRep(){ 
  let randomReps = [`4x10`,`4x8`, `4x20`, `4x12`, `4x15`,`3x10`, `3x15`, `4x5`, `5x10`, `10x10`];
  for(let i=0; i < 5; i++){
  let randomNr = Math.floor(Math.random() * maxNr); 
  if (randomNr==9) maxNr=9;
  let repsText = "<li>"+randomReps[randomNr]+"</li>";
  document.getElementById("repsList").innerHTML+=repsText;
  console.log(maxNr);
 }
}

//THIS IS A SHUFFLE FUNCTION 

function shuffle(array) {
  let currentIndex = array.length,  randomIndex;
  // While there remain elements to shuffle...
  while (currentIndex != 0) {
    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex--;
    // And swap it with the current element.
    [array[currentIndex], array[randomIndex]] = [
      array[randomIndex], array[currentIndex]];
  }
  return array;
}

//This is the workout generator for, in this case, a chest and back workout using the shuffle function from above.

function generateWorkout() {
  let workoutList = [`Chins`, `Wide barbell row (bent over)`, `Row with machine`, `Cable pulldown`,
  `Lat pulldown`, `Bent-over dumbbell alternating row`,`Reverse fly with barbell`,`Push-ups`, 
  `Face-pull with cable`, `Seated face pull`, `Single arm lat pulldown`, `Low position row with cable`, 
  `Split stance high anchor row with cable`, `Bench Press`, `Overhead press with dumbbells or barbell`,
  ` One arm row with dumbbell`,` Inverted row`, `Close grip dumbbell press`, ];
  let shuffleWorkoutList= shuffle(workoutList);
  for(let i=0; i < 5; i++){
    let workoutText = "<li>"+workoutList[i]+"</li>";
    document.getElementById("listOfWorkouts").innerHTML+=workoutText;
  }
} ```
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The syntax of using the LocalStorage is

  • save a value: localStorage.setItem("name-or-key", "value") where the key and value should be strings.
  • get a value: localStorage.getItem("name-or-key")

This is how you could implement this in your snippet:

function generateWorkout() {
  let workoutList = [`Chins`, `Wide barbell row (bent over)`, `Row with machine`, `Cable pulldown`,
  `Lat pulldown`, `Bent-over dumbbell alternating row`,`Reverse fly with barbell`,`Push-ups`, 
  `Face-pull with cable`, `Seated face pull`, `Single arm lat pulldown`, `Low position row with cable`, 
  `Split stance high anchor row with cable`, `Bench Press`, `Overhead press with dumbbells or barbell`,
  ` One arm row with dumbbell`,` Inverted row`, `Close grip dumbbell press`, ];
  let shuffleWorkoutList= shuffle(workoutList);
  for(let i=0; i < 5; i++){
    let workoutText = "<li>"+workoutList[i]+"</li>";
  };
  localStorage.setItem("workout-list", workoutList.join(","));
};

and

function load_prev_workout() {
    const prev_workout = localStorage.getItem("workout-list").split(",");
    console.log(prev_workout);
    for(let i=0; i < 5; i++){
        let workoutText = "<li>"+prev_workout[i]+"</li>";
        console.log("Now use this:",workoutText,"for something.");
    };
};

Then call these conditionally:

if(localStorage.getItem("workout-list")) {
    load_prev_workout();
} else {
    generateWorkout();
};

If you want to save more than one workout at a time, let the user choose a name for that workout, or give it a unique id, then use that as part of the localStorage item's name/key

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda