Jump to content

Unable to loop through JavaScript program more than once (JavaScript beginner)

Go to solution Solved by duncannah,

The story is already created before you run result(), so running the result() function again won't create a new one.

 

All you need to do is to put the new story initiation into the function like so:

1918824717_Image2022-06-102PM-37-15.png.12dfcfcc4d8cced7d978bf7b2e060c6f.png

Hi I'm using a .html and .js file

Languages: HTML, CSS, JavaScript
Level: Beginner

 

Problem:

Unable to loop through JavaScript program more than once (aka change custom name a second time or changing from us to uk)

I managed to fix all my problems to get the program to work but I do not know why it only works one time..

 

Short info about the program:

It generates a short story where Bob is replaced by your custom name and it can translate fahrenheit and pounds to celsius and kg

If you would like to make this program yourself just google Mozilla Javascript (the course) silly story generator (the assignment to test your beginner skills) or something similar.

 

Html

Spoiler
  <body>
      <div>
          <label for="customname">Enter custom name:</label>
          <input id="customname" type="text" placeholder="">
    </div>
    <div>
        <label for="us">US</label>
        <input id="us" type="radio" name="ukus" value="us" checked>
        <label for="uk">UK</label>
        <input id="uk" type="radio" name="ukus" value="uk">
    </div>
    <div>
        <button class="randomize">Generate random story</button>
    </div>
    <!-- Thanks a lot to Willy Aguirre for his help 
        with the code for this assessment -->
    <p class="story"></p>
    

    <script src="main.js"></script>

CSS

Spoiler
    body {
        font-family: helvetica, sans-serif;
        width: 350px;}

    label {
        font-weight: bold;  }

    div {
        padding-bottom: 20px;}

    input [type="text"] {
        padding: 5px;
        width: 150px;}

    p {
        background: #FFC125;
        color: #5E2612;
        padding: 10px;
        visibility: hidden;}

JavaScript

Spoiler
// 1. COMPLETE VARIABLE AND FUNCTION DEFINITIONS

var customName = document.getElementById('customname');
var randomize = document.querySelector('.randomize');
var story = document.querySelector('.story');

function randomValueFromArray(array) {
  const random = Math.floor(Math.random()*array.length);
  return array[random];}

// 2. RAW TEXT STRINGS

var storyText = 'It was 94 fahrenheit outside, so :insertx: went for a walk.'+
'When they got to :inserty:, they stared in horror for a few moments,'+
'then :insertz:. Bob saw the whole thing,'+
'but was not surprised — :insertx: weighs 300 pounds, and it was a hot day.';
  
var insertX = ['Willy the Goblin', 'Big Daddy', 'Father Christmas'];
  
var insertY = ['the soup kitchen', 'Disneyland','the White House'];
  
var insertZ = ['spontaneously combusted',
'melted into a puddle on the sidewalk',
'turned into a slug and crawled away'];

// 3. EVENT LISTENER AND PARTIAL FUNCTION DEFINITION

randomize.addEventListener('click', result);

var newStory = storyText;
var xItem = randomValueFromArray(insertX); 
var yItem = randomValueFromArray(insertY); 
var zItem = randomValueFromArray(insertZ);

newStory = newStory.replaceAll(':insertx:', xItem);  
newStory = newStory.replaceAll(':inserty:', yItem); 
newStory = newStory.replaceAll(':insertz:', zItem);    

function result() {

  if(customName.value !== '') {
      const name = customName.value;
      newStory = newStory.replace('Bob', name);}

  if(document.getElementById("uk").checked) {
      const weight = Math.round(300*0.45359237) + ' kg'; 
      // Lbs*0.45 = kg
      const temperature =  Math.round((94-32)/1.8) + ' celsius'; 
      // (Fahrenheit-32)/1.8 = celsius
        
      newStory = newStory.replace('94 fahrenheit', temperature); 
      newStory = newStory.replace('300 pounds', weight);
    }

  story.textContent = newStory;
  story.style.visibility = 'visible';}

 

 

PC  Specs 2022:

Spoiler
  • CPU
    AMD Ryzen R9 5900x @ 5.1GHz - Auto OC
  • Curve Optimizer Magnitude: -20
  • Motherboard
    ASUS ROG STRIX x570-F Gaming
  • RAM
                                        Kingston Fury 32GB DDR4 3200MHz 16x2GB
  • GPU
    MSI 3070 8GB Ventus 2x OC
  • Case
    LIAN LI LANCOOL MESH II Mesh RGB Black
  • Storage
    Kingston NV1 2TB M.2. NVMe
  • PSU
    Seasonic Focus GX 850w 
  • Display(s)
    MSI OPTIX MAG 251RX IPS 240hz & ASUS MG248Q Vertical 144hz & Dell 60hz
  • Cooling
    NZXT Kraken x73 360mm
  • Keyboard
    Tt eSports Meka G1
  • Mouse
    Logitech G Pro Wireless
  • Operating System
    -Windows 10 Professional 64bit
Link to comment
Share on other sites

Link to post
Share on other sites

The story is already created before you run result(), so running the result() function again won't create a new one.

 

All you need to do is to put the new story initiation into the function like so:

1918824717_Image2022-06-102PM-37-15.png.12dfcfcc4d8cced7d978bf7b2e060c6f.png

🙂

Link to comment
Share on other sites

Link to post
Share on other sites

NVM it works, thank you

 

JavaScript

Spoiler
// SNIP

// 3. EVENT LISTENER AND PARTIAL FUNCTION DEFINITION

randomize.addEventListener('click', result);

var newStory = storyText;
var xItem = randomValueFromArray(insertX); 
var yItem = randomValueFromArray(insertY); 
var zItem = randomValueFromArray(insertZ);

newStory = newStory.replaceAll(':insertx:', xItem);  
newStory = newStory.replaceAll(':inserty:', yItem); 
newStory = newStory.replaceAll(':insertz:', zItem);    

function result() {
  var newStory = storyText;
var xItem = randomValueFromArray(insertX); 
var yItem = randomValueFromArray(insertY); 
var zItem = randomValueFromArray(insertZ);

newStory = newStory.replaceAll(':insertx:', xItem);  
newStory = newStory.replaceAll(':inserty:', yItem); 
newStory = newStory.replaceAll(':insertz:', zItem); 

  if(customName.value !== '') {
      const name = customName.value;
      newStory = newStory.replace('Bob', name);}

  if(document.getElementById("uk").checked) {
      const weight = Math.round(300*0.45359237) + ' kg'; 
      // Lbs*0.45 = kg
      const temperature =  Math.round((94-32)/1.8) + ' celsius'; 
      // (Fahrenheit-32)/1.8 = celsius
        
      newStory = newStory.replace('94 fahrenheit', temperature); 
      newStory = newStory.replace('300 pounds', weight);
    }

  story.textContent = newStory;
  story.style.visibility = 'visible';}

 

 

PC  Specs 2022:

Spoiler
  • CPU
    AMD Ryzen R9 5900x @ 5.1GHz - Auto OC
  • Curve Optimizer Magnitude: -20
  • Motherboard
    ASUS ROG STRIX x570-F Gaming
  • RAM
                                        Kingston Fury 32GB DDR4 3200MHz 16x2GB
  • GPU
    MSI 3070 8GB Ventus 2x OC
  • Case
    LIAN LI LANCOOL MESH II Mesh RGB Black
  • Storage
    Kingston NV1 2TB M.2. NVMe
  • PSU
    Seasonic Focus GX 850w 
  • Display(s)
    MSI OPTIX MAG 251RX IPS 240hz & ASUS MG248Q Vertical 144hz & Dell 60hz
  • Cooling
    NZXT Kraken x73 360mm
  • Keyboard
    Tt eSports Meka G1
  • Mouse
    Logitech G Pro Wireless
  • Operating System
    -Windows 10 Professional 64bit
Link to comment
Share on other sites

Link to post
Share on other sites

6 minutes ago, c0d0ps said:

Hi thanks for answer,

only problem with this is my randomValueFromArray() stops working when inside this function

How did you come to that conclusion? I just did what duncannah recommended and it works fine for me.

 

JS:

// 2. RAW TEXT STRINGS

var storyText = 'It was 94 fahrenheit outside, so :insertx: went for a walk.'+
'When they got to :inserty:, they stared in horror for a few moments,'+
'then :insertz:. Bob saw the whole thing,'+
'but was not surprised — :insertx: weighs 300 pounds, and it was a hot day.';
  
var insertX = ['Willy the Goblin', 'Big Daddy', 'Father Christmas'];
  
var insertY = ['the soup kitchen', 'Disneyland','the White House'];
  
var insertZ = ['spontaneously combusted',
'melted into a puddle on the sidewalk',
'turned into a slug and crawled away'];

// 3. EVENT LISTENER AND PARTIAL FUNCTION DEFINITION

randomize.addEventListener('click', result);

function result() {

    var newStory = storyText;
	var xItem = randomValueFromArray(insertX); 
	var yItem = randomValueFromArray(insertY); 
	var zItem = randomValueFromArray(insertZ);

	newStory = newStory.replaceAll(':insertx:', xItem);  
	newStory = newStory.replaceAll(':inserty:', yItem); 
	newStory = newStory.replaceAll(':insertz:', zItem);    

  if(customName.value !== '') {
      const name = customName.value;
      newStory = newStory.replace('Bob', name);}

  if(document.getElementById("uk").checked) {
      const weight = Math.round(300*0.45359237) + ' kg'; 
      // Lbs*0.45 = kg
      const temperature =  Math.round((94-32)/1.8) + ' celsius'; 
      // (Fahrenheit-32)/1.8 = celsius
        
      newStory = newStory.replace('94 fahrenheit', temperature); 
      newStory = newStory.replace('300 pounds', weight);
    }

  story.textContent = newStory;
  story.style.visibility = 'visible';}

 

 

On 4/5/2024 at 10:13 PM, LAwLz said:

I am getting pretty fucking sick and tired of the "watch something else" responses. It's such a cop out answer because you could say that about basically anything, and it doesn't address the actual complaints. People use it as some kind of card they pull when they can't actually respond to the criticism raised but they still feel like they need to defend some company/person. If you don't like this thread then stop reading it. See how stupid it is? It's basically like telling someone "shut the fuck up". It's not a clever responsive, it doesn't address anything said, and it is rude. 

 ^

 

bruh switch to dark mode its at the bottom of this page

VPN Server Guide

Link to comment
Share on other sites

Link to post
Share on other sites

4 minutes ago, RockSolid1106 said:

How did you come to that conclusion? I just did what duncannah recommended and it works fine for me.

 

JS:

SNIP

Hi I forgot to everything under 

    var newStory = storyText;
	var xItem = randomValueFromArray(insertX); 
	var yItem = randomValueFromArray(insertY); 
	var zItem = randomValueFromArray(insertZ);

when I updated my comment I managed to fix it, thank you

PC  Specs 2022:

Spoiler
  • CPU
    AMD Ryzen R9 5900x @ 5.1GHz - Auto OC
  • Curve Optimizer Magnitude: -20
  • Motherboard
    ASUS ROG STRIX x570-F Gaming
  • RAM
                                        Kingston Fury 32GB DDR4 3200MHz 16x2GB
  • GPU
    MSI 3070 8GB Ventus 2x OC
  • Case
    LIAN LI LANCOOL MESH II Mesh RGB Black
  • Storage
    Kingston NV1 2TB M.2. NVMe
  • PSU
    Seasonic Focus GX 850w 
  • Display(s)
    MSI OPTIX MAG 251RX IPS 240hz & ASUS MG248Q Vertical 144hz & Dell 60hz
  • Cooling
    NZXT Kraken x73 360mm
  • Keyboard
    Tt eSports Meka G1
  • Mouse
    Logitech G Pro Wireless
  • Operating System
    -Windows 10 Professional 64bit
Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×