"Silly story generator" assessment


(Chris Mills) #21

@bishals is right - this should be querySelector, as it is selecting by the CSS class selector .randomize, not the actual class name, which is randomize.

Also, getElementsByClassName returns an array containing multiple element references, whereas querySelector returns a single element reference — the first element in the document that matches the provided selector.

Therefore the first one won’t work, but the second will.


(jennoskl) #22

I don’t understand this at all. I am using

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

just like you and several other people have suggested, and I keep getting the error

“randomize is null”

to be honest, I don’t think I have any idea of what I am doing, I am trying to follow people’s advice and not getting anywhere.


(Chris Mills) #23

I am sure there must be a simple explanation here. Can you send me your version of the code?

Send it to me at cmills@mozilla.com, and I’ll help you work out what’s wrong.


(Ameerkabir2) #24

HI everyone here is my version of selly story it seems to be not working help pleas? 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)];
    
    //the flowing three varabkes contains the randome text of the story 
    
    var storyTex = "It was 94 farenheit 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 he was not surprised — :insertx: weighs 300 pounds, and it was a hot day."
    
    var stringX = ["Willy the Goblin","Big Daddy","Father Christmas"];
    
    var stringY = ["the soukitchen","Disneyland","the White House"];
    
    var stringZ = ["spontaneously combusted","melted into a puddle on the sidewalk","turned into a slug and crawled away"];
  
    
    randomize.addEventListener('click', result);

    function result() {

      if(customName.value != '') {
        var name = customName.value;
        newStory = newStory.replace("Bob",variable);

      }

      if(document.getElementById("uk").checked) {
        var weight = Math.round(300 * 0.071429) + "stone";
        var temperature =  Math.round(94-32*.5556) + "centigrade";
        newStory.replace("weight","94 farenheit")
        newStory.replace("temperature", "300 pounds")

      }

      story.textContent = ;
      story.style.visibility = 'visible';
      
      var newStory = storyTex;
      var xItem = stringX;
    
      var yItem = stringY;
      
      var zItem = stringZ;
      newStory = newStroy.replace(":insertx:", stringX);
      newStory = newStory.replace(":inserty:", stringY);
      newStory = newStory.replace(":insertz:", stringZ);
        story = newStory;
      
      
    }
    
  }
</script>

(Chris Mills) #25

Hi there!

From a quick glance, it looks like there are some spelling and other errors in the code that would need to be fixed before the example will work properly. Compare your code with the finished code at https://github.com/mdn/learning-area/blob/master/javascript/introduction-to-js-1/assessment-finished/main.js.

also, as a hint, search for these errors in your code:

  • storyTex (this appears a couple of times)
  • newStroy
  • The randomValueFromArray() function does not have a closing curly brace.

Let me know if you need any more help. Thanks!


(Henry Grant) #26

Hi there,

May I please have the marking guide for the Silly Story Generator?

Thanks,

RHG


(Chris Mills) #27

Hi Henry,

Sure thing — no worries! You can find what you need below:

Please let me know if you have any more questions.

All the best,

Chris


#28

Hi Folks. Apologies but completely new to this and cant get silly story generator to work. The original story text keeps showing up when I click the button to generate a random story i.e. nothing gets replaced. My code is below. If anyone has any ideas as to why its not working I would appreciate it.

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)];
}

var storyText = ‘It was 94 farenheit 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 he 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’];

randomize.addEventListener(‘click’, result);

function result() {

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

newStory.replace(’:insertx:’, xItem);
newStory.replace(’:inserty:’, yItem);
newStory.replace(’:insertz:’, zItem);
newStory.replace(’:insertx:’, xItem);

if(customName.value != ‘’) {
var name = customName.value;
newStory.replace(‘Bob’, name);
}

if(document.getElementById(“uk”).checked) {
var weight = Math.round(300*.0714286) + ‘stones’;
var temperature = Math.round(94-32) + ‘centigrade’;
newStory.replace(‘94 farenheit’, temperature);
newStory.replace(‘300 pounds’, weight);

}

story.textContent = newStory;
story.style.visibility = ‘visible’;
}


(Tom Rooker) #29

Hi everyone - this is probably a really basic question, but just want to make sure I fully understand the script with this.

Could anyone explain the following syntax:

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

My instinct was to write newStory.replace(’:insertx:’, xItem); without the =, so just wondering why the first bit of the declaration is necessary?

Thanks for you help.


(adilson) #30

Hi there!
These are my JS Code and live preview of this assessment.

I haven’t compared it to chri’s code yet, but I don’t think there’s too much of a difference (steps were very specific and clear). Just two things that I made, and worth to point out:

  1. I used global RegExp as argument in the replace string method to replace all matches at once, instead of calling two times replace as the guide suggested.

  2. This one was funny :sweat_smile:… while writing my code I thought that the user could write white spaces in the text field (beginning or end) and it could ruin the story structure, so I decided to make use of the trim method which gave me the desired results. But! when I came to the forum and started checking other fellow’s codes and tested them I noticed that even if they didn’t considered such cases and I entered names with leading/trailing spaces, the story didn’t show any extra spaces anyway.
    I was thrilled! So I tried to track down the reason of that… till I realized and remembered one of the first lessons of this guide about HTML parser ignoring extra spaces :rofl: .


(Chris Mills) #32

Hi Tom,

Sorry for missing this post for so long.

This is a confusing one — basically, you need to write it like this because the replace() method creates a new copy of the string with the replacement made in it, rather than just making the replacement in the existing copy.

So if we just do newStory.replace(’:insertx:’, xItem);, it will create the new copy but not apply it to anything.

Doing newStory = newStory.replace(’:insertx:’, xItem); means thatit will create the new copy, and them immediately write it over the top of the existing newStory variable value.


(Chris Mills) #33

This is a really interesting point to bring up. The main reason I’ve not used the regex version is that I was worried regexes would be too complex for the beginner’s course. But I am open to opinions :wink:


(Taksh) #34

I coded this assessment but am facing a debugging issue. Although, everything seems fine with my code when I open my HTML file I get an undefined error in the story area.

Here’s my code:

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)];

}

var storyText = ‘It was 94 farenheit 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 he 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’];

randomize.addEventListener(‘click’, result);

function result() {

var newStory = storyText;
var xItem = randomValueFromArray(insertX);
var yItem = randomValueFromArray(insertY);
var 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 != '') {

    var name = customName.value;
    newStory = newStory.replace('Bob', name);
}

if (document.getElementById("uk").checked) {

    var weight = Math.round(300);

    var temperature = Math.round(94);

    weight *= 0.0714286;
    temperature = (5 / 9) * (temperature - 32);
    var temp = temperature + ' celsius';
    storyText = storyText.replace('94 farenheit', temp);
    temp = weight + ' stones';
    storyText = storyText.replace('300 pounds',weight );
}

story.textContent = newStory;

story.style.visibility = 'visible';

}

Thanks in advance.


(Chris Mills) #35

Hi there @Taksh ,

Thanks for getting in touch!

I have tried your code out in my local version of the example, and it looks like it works mostly OK, except that the weight and temperature conversion goes a bit wrong. Have a look at the final block and see how it compares to yours:

  if(document.getElementById("uk").checked) {
    var weight = Math.round(300*0.0714286) + ' stone';
    var temperature =  Math.round((94-32) * 5 / 9) + ' centigrade';
    newStory = newStory.replace('94 farenheit',temperature);
    newStory = newStory.replace('300 pounds',weight);
  }

I think the problem is mainly that you’re replacing the values inside storyText, not newStory.

A couple of other minor points:

  1. For comparison, always use the strict version of the operator, so for example in this case, do customName.value !== '' — two equals, not 1. You get less errors this way, as it will only return true if the compared values are the same value AND data type.

  2. In your series of replace lines, you need a extra colon on the end of each value you are replacing, so for example :insertx: rather than :insertx.


(Tom Rooker) #36

Thanks for getting back Chris and taking the time to explain - that’s massively helped and makes perfect sense now. Thanks again!


(Chris Mills) #37

You are welcome @tomdrooker !


(adilson) #38

Well I only read over mdn’s article and understood enough and a little more to apply it in our assessment, I’ll give it a deeper check once I encountered them again. And about using it in this module, it’s not a bad idea, you could mention “using regex” as an alternative to the task you asked and then leave us to find out how to use it, in case we are interested.

In my experience, when I read the hint you gave us about calling the replace method twice I thought to my self: there must be another way. Then I googled, found out about regex, came back to MDN (I prefer reading here at least all the basics, it’s super well structured and exemplified, kudos for you all) and found the article linked before.


(Chris Mills) #39

Cool, thanks for the further commentary. I’ve noted this down in my plan for 2018 tutorial updates, and will add at least a mention and link in (to the main regexs guide) when the time comes.


(Gnanavelv27) #40

hello there,
I have used same code from github:https://github.com/mdn/learning-area/blob/master/javascript/introduction-to-js-1/assessment-finished/main.js

I am getting typeerror:customName is null

why is it
need some fix and explanation new to JS


(Steven) #41

Hi, i would like to request for marking guide on my code below for the exercise “Silly story generator”, thank you very much =)

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

var storyText ="It was 94 farenheit 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 he 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"];

randomize.addEventListener('click', result);

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

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

  if(customName.value != '') {
    var name = customName.value;
    randomName = storyText.replace("Bob", name);
	newStory = randomName;
  }

  if(document.getElementById("uk").checked) {
    var weight = Math.round(300*0.0714286);
    var temperature =  Math.round((94-32)*.5556);
	ukTemp = newStory.replace("94", temperature + " centigrade").replace("300 pounds", weight + " stones");
    newStory = ukTemp
  }
  story.textContent = newStory.replace(":insertx:", xItem).replace(":insertx:", xItem).replace(":inserty:", yItem).replace(":insertz:", zItem);
  story.style.visibility = 'visible';
}