"Silly story generator" assessment

Gotcha!


<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width">
    <title>笑话生成器</title>
    <link rel="stylesheet" href="styles/joke.css">
    <script src="joke.js" defer></script>
  </head>

  <body>
    <div>
      <label for="customname" id="lbl-customname">请输入自定义的名字:</label>
      <input id="customname" type="text" placeholder="李雷">
    </div>
    <div>
      <label for="cn" id="lbl-cn">中国</label><input id="cn" type="radio" name="country" value="cn" checked>
      <label for="us" id="lbl-us">美国</label><input id="us" type="radio" name="country" value="us">
      <label for="uk" id="lbl-uk">英国</label><input id="uk" type="radio" name="country" value="uk">
  </div>
  <div>
      <button class="randomize">随机生成笑话</button>
  </div>

  <p class="story"></p>
  <script src="scripts/joke.js"></script>
    
</body>
</html>

@lsyh1210 great, thanks, now I can test it.

It is working perfect, well done!

And I love the extra Chinese option!

:)

chrisdavidmills via Mozilla Discourse notifications@discourse.mozilla.org于2019年11月11日 周一03:05写道:

Hi everyone,
I will share my code with you.
If you have any comments about him, please comment.
Have fun.

//////////////////////////////////////////////////////////////////////

// 1. COMPLETE VARIABLE AND FUNCTION DEFINITIONS

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

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

// 2. RAW TEXT STRINGS

let 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: weights 300 pounds, and it was a hot day.'

let insertX = ['Willy the Goblin',
              'Big Daddy',
              'Father Christmas'];

let insertY = ['the soup kitchen',
              'Disneyland',
              'the White House'];

let 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() {
let newStory = storyText;
let xItem = randomValueFromArray(insertX);
let yItem = randomValueFromArray(insertY);
let zItem = randomValueFromArray(insertZ);
newStory = newStory.replace(/:insertx:/g, randomValueFromArray(insertX));
newStory = newStory.replace(':inserty:', randomValueFromArray(insertY));
newStory = newStory.replace(':insertz:', randomValueFromArray(insertZ));

  if(customName.value !== '') {
    var name = customName.value;
    newStory = newStory.replace('Bob', customName.value);
  }
  
  if(document.getElementById("uk").checked) {
    var weight = Math.round(300 / 1.40000) + ' stone';
    var temperature =  Math.round((94 - 32) / 1.800000) + ' centigrade';
    newStory = newStory.replace('300 pounds',  Math.round(300 / 14.00000) + ' stone');
    newStory = newStory.replace('94 fahrenheit', Math.round((94 - 32) / 1.800000) + ' centigrade');
  }
  

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

Hi there @B.S_Budniok, and thanks for sending your code in!

I’ve tested this, and it seems to work perfectly; it does everything it’s supposed to do, and runs fine.

Well done on some great work.

I have completed this assessment and my code is working perfectly. I really enjoyed this module.

One thing I noticed by reading all of these posts… I did not know that we could stack functions/methods(?) on top of one another. Like so,

newStory = newStory.replace().replace().replace();

When is this allowed and when is it not?

@mbrasseau cool, glad you enjoyed it!

Generally chaining method calls together works when the previous method call has a return value that can have the next method call can be called on. So in the above chain, replace() works on strings; it wouldn’t work if one of the items in the chain returned a number, for example.

1 Like
const customName = document.getElementById('customname');

const randomize = document.querySelector('.randomize');

const story = document.querySelector('.story');

function randomValueFromArray(array){

  const random = Math.floor(Math.random()*array.length);

  return array[random];

}

let 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.';

let insertX = ['Willy the Goblin','Big Daddy','Father Christmas'];

let insertY = ['the soup kitchen','Disneyland','the White House'];

let insertZ = ['spontaneously combusted','melted into a puddle on the sidewalk','turned into a slug and crawled away'];

randomize.addEventListener('click', result);

function result() {

  let newStory = storyText;

  let xItem = randomValueFromArray(insertX);

  let yItem = randomValueFromArray(insertY);

  let zItem = randomValueFromArray(insertZ);

  newStory = newStory.replace(':insertx:',xItem);

  newStory = newStory.replace(':insertx:',xItem);

  newStory = newStory.replace(':inserty:',yItem);

  newStory = newStory.replace(':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.0714286) + ' stone';

    const temperature =  Math.round((94-32) * 5 / 9) + ' centigrade';

    newStory = newStory.replace('94 fahrenheit',temperature);

    newStory = newStory.replace('300 pounds',weight);

  }

  story.textContent = newStory;

  story.style.visibility = 'visible';

}

why this
“Cannot read property ‘addEventListener’ of null”

Hello my teacher, @chrisdavidmills I don’t know, what is problem at my code?

Hi there @Bumidu_yasith!

I tried out your code in my example, and it worked fine.

If you are getting the error “Cannot read property ‘addEventListener’ of null”, then it must relate to this line:

randomize.addEventListener('click', result);

It is saying that randomize has a value of null, which means it isn’t being set properly. We are setting the value of randomize in this line:

const randomize = document.querySelector('.randomize');

which should select and store a reference to the following button inside the HTML:

<button class="randomize">Generate random story</button>

does your random story button have class="randomize" included on it?

Hi there @krasnovdanial, hope you are well.

This is a pretty easy fix. When you run your app and open the devtools, the JS console gives an error of “Loading failed for the with source “https://chartreuse-monkey.glitch.me/JS/script.js””, which indicates that you are simply pointing at the wrong location for the script.

Removing JS/ will cause the script to load correctly.

After that you’ve got a couple of errors in your JS to fix, and it should work. Again, look at the error messages in the DevTools JS console to help you.

Hi there @chrisdavidmills, yes i’m well.
Please tell me, since I study everything on my own, I have problems with checking the site for adaptability and structure, some questions arise. Is it possible to throw off here, maybe you will have time? And I also wanted to ask after what points it is worth going to freelance, after what skills learned here? Is it worth all your messages to go to freelance already? Thank you very much for the great feedback.

Is it possible to throw off here, maybe you will have time?

I’m not 100% sure what you mean, but it sounds like you are asking me if i’d answer some more questions. I am always happy to help people, as long as I have the time. You can always ask me, but I might not have time, so let’s see how it goes!

And I also wanted to ask after what points it is worth going to freelance, after what skills learned here? Is it worth all your messages to go to freelance already?

So you are asking if you should try being a freelancer, with the knowledge you currently have? I can’t really answer that question for you.

Hi, Chris look it please https://wax-virgo.glitch.me
Why aren’t my images and footer icons inserted in my glitch? And how can I improve my website?

Why aren’t my images and footer icons inserted in my glitch

The paths to your images in your src attributes are probably wrong. At the moment, you just have the image filename as the path. Are your images contained in a subfolder?

And how can I improve my website?

For the moment, this looks clean and simple, and spacious. I like it. I’d add things very slowly and carefully, thinking about what you actually really need. There is nothing worse than a website with far too much on it — it quickly starts to look cluttered.

Make sure the most important things have the biggest “visual weight” on the page, so the reader’s eye is drawn to them. You are already doing this quite nicely, with the “Hire me” button, etc. Maybe have the important information a bit higher up - at the moment you have to scroll down a whole page height to see anything “useful”.

Hi its 2022 now lol, guys i see everyone uses .replace to change the history values, but i did it in other way, the var newStory transformed the string into an array by dividing the items using the ‘:’, so i was able to replace the inserX,Y,Z just by its position, here is the code:

const customName = document.getElementById(‘customname’);

const randomize = document.querySelector(’.randomize’);

const story = document.querySelector(’.story’);

function randomValueFromArray(array){

const random = Math.floor(Math.random()*array.length);

return array[random];

}

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.’;

insertX = [‘Willy the Goblin’,‘Big Daddy’,‘Father Christmas’];

insertY = [‘the soup kitchen’,‘Disneyland’,‘the White House’];

insertZ = [‘spontaneously combusted’,‘melted into a puddle on the sidewalk’,‘turned into a slug and crawled away’],

randomize.addEventListener(‘click’, result);

function result() {

let newStory = storyText.split(':');

xItem = randomValueFromArray(insertX);

yItem = randomValueFromArray(insertY);

zItem = randomValueFromArray(insertZ);

newStory[1] = xItem;

newStory[3] = yItem;

newStory[5] = zItem;

newStory[7] = xItem;

if(customName.value !== ‘’) {

const name = customName.value;

newStory[6] =' ' + name + ' saw the whole thing, but was not surprised';

}

if(document.getElementById(“uk”).checked) {

const weight = Math.round(300);

const temperature =  Math.round(94);

const temperatureC = Math.round((temperature - 32) * 5/9);

console.log(temperatureC);

newStory[0] = 'It was ' + temperatureC + ' celcius outside, so '

const weightUk = Math.round(weight / 14);

newStory[8] = 'weighs ' + weightUk + ' stones, and it was a hot day';

}

story.textContent = newStory;

story.style.visibility = ‘visible’;

console.log(newStory);

}

Hi @HernanSDEV and welcome to the community :wave:

That’s certainly a creative way to solve the problem, but maybe not the most practical one. :grin:

Michael

Hello, I am learning javascript in a self-taught way and I need the qualification guide. I have finished the evaluation code. It has taken me days but I achieved it. Thanks, I leave the sample

file.js

image

image

result

Hi @boboxxdingo

Nice work! :clap:

As far as I can tell everything looks fine.

By the way, if you plan on doing more tasks it would be helpful if you could share your code in an online editor like https://codepen.io/, https://glitch.com or https://jsfiddle.net/. It’s much easier for us if we can see the result and test things out if necessary. Thank you :blush:

Have a nice day,
Michael

Hi I’ve just completed the Silly story generator on the javascript first steps, can someone please assess my code:

   'use strip'

   // 1. 定义变量和函数

   const customName = document.getElementById('customname')

   const randomize = document.querySelector('.randomize')

   const story = document.querySelector('.story')

   const defaultName = 'Bob'

   customName.setAttribute('placeholder', defaultName)

   // 2. 纯文本字符串

   const storyText = `\

   今天气温 {temperature}, \

   {who}出去遛弯。\

   当走到{where}门前时, \

   突然就{what}。\

   人们都惊呆了, \

   {name}全程目睹但并没有慌, \

   因为{who}是一个 {weight}的胖子, \

   天气又辣么热。\

   `

   const insertX = ['怪兽威力', '大老爹', '圣诞老人']

   const insertY = ['肯德基', '迪士尼乐园', '白宫']

   const insertZ = ['自然了', '在人行道化成了一坨泥', '变成一条鼻涕虫爬走了']

   // 3. 事件监听器和未完成的函数定义

   randomize.addEventListener('click', event => {

       let isAmerican = document.getElementById('american').checked

       let weight = !isAmerican ? Math.round(140) + ' 公斤' : Math.round(309) + ' 磅'

       let temperature = isAmerican ? Math.round(95) + ' 华氏度' : Math.round(35) + ' 摄氏度'

       let name = customName.value === '' ? defaultName : customName.value

       let who = randomValueFromArray(insertX)

       let where = randomValueFromArray(insertY)

       let what = randomValueFromArray(insertZ)

       story.textContent = storyText

           .replaceAll('{name}', name)

           .replaceAll('{weight}', weight)

           .replaceAll('{temperature}', temperature)

           .replaceAll('{who}', who)

           .replaceAll('{where}', where)

           .replaceAll('{what}', what)

       story.style.visibility = 'visible'

   })

   function randomValueFromArray(array) {

       return array[Math.floor(Math.random() * array.length)]

   }