"Silly story generator" assessment

@gnanavelv27 The link you provided is the solved one (by chris). Could you share your JS code and the html one as well?. If you are getting a null value with customName, it means that either you didn’t add the right id property into the html element or the declaration at your JS code is wrong.

@sent2steven I tried your JS code, and I think it works perfectly. The way you implemented it is quite different from the one solved or the one I made, but I kinda liked it. Specially the line where you added a series of replace methods one after the other :rofl:. But, if you allow me, I think it could have been better to make those replacements in the line 14th over the variable storyText and assign it to newStory, in that way you could use newStory to fill the paragraph and other future features of your code.

Anyway, kudos for you!! you did it great :blush:

Thank you so much! Glad that i pass the test! I had been self studies JavaScript from w3chools few weeks ago but i still barely can understand or write some good code, then i found here, definitely i gain more understanding on what Javascript is and how to write it from scratch. It helps me a lots on improve my Javascript skill. Thanks MDN for the great tutorial providing here! Moving on to the next assessment and i hope i will get there soon!

1 Like

Hello adilson,
Thank you for the response and I have checked my html and js code for wrong ID but I have given right propery for both.
I have shared my code below main.js

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

var randomize = document.getElementsByClassName(’.randomize’);

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

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’, ‘white house’];
var insertz = [‘spontaneously combusted’, ‘melted into a puddle on the side walk’, ‘turn into a slug and crawled away’];

randomize.addEventListener(‘click’, result());

function result()
{
var newStory = storyText;

var xtext = randomValue(insertx);
var ytext = randomValue(inserty);
var ztext = randomValue(insertz);

newStory = newStory.replace(’:insertX:’, xtext);
newStory = newStory.replace(’:insertY:’, ytext);
newStory = newStory.replace(’:insertZ:’, ztext);

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

}

if(document.getElementById(‘uk’).checked){
var weight = math.round(300*0.71) + ‘stone’;
var temperature = math.round((94-32) * 5 / 9) + ‘centigrade’;
newStory = newStory.replace(‘300pounds’,weight);
newStory = newStory.replace(‘94 farenheit’, temperature);

}

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

I have shared my index.html file also below this

Silly story generator
Enter custom name:
US UK
Generate random story
<p class="story"></p>
error also I have added in screenshot: ![error|690x176](upload://f75uMvtcMwVD7PHfr4LCBie5tFQ.png)

@2alin sorry I haven’t send my HTML file .

<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width">
<script type="text/javascript" src = 'main.js'></script>
<title>Silly story generator</title>
 </head>

<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>

<p class="story"></p>
</body>
</html>`

@gnanavelv27 thanks for sharing your code :grinning:, I have checked it already and there’s a bunch of problems in there, but let’s try to fix them one by one.
First, with your html code:

  1. If you are writing your code locally in a suitable editor, you need to always add <!DOCTYPE html> all the way to the top of your html file, that’s used to indicate the browser that your document is an html5 one and avoid problems with some tags. But, if you are using an online editor, probably you won’t need to add it. Check that please.

  2. The <script> element must go almost at the bottom of your document, just before your closing </body>. Not at the top, like <link>.

  3. All the css code (<style>) that came in the original html file that chris asked us to use is gone from your file, where did you put it? Are you using an online editor?

Now the JS code:

  1. In line 3, you are using getElementsByClassName which needs as argument the name of the class, nothing more (dots or hashtaghs are not needed there). But getElementsByClassName returns a list of elements, and we need THE element. So you have two options, either use document.querySelector('.randomize') or use getElementsByClassName('randomize')[0]… your choice, both will work.

  2. In line 15, the second argument of addEventListener is only the name of the function without parenthesis (remove them, please).

  3. From line 25 to 27, it’s :insertx: , :inserty: and :insertz:, last character in lowercase not capital . That’s how it appears in storyText, and it’s what we want to replace. Also, repeat the line with :insertx:, because it appears twice in the text.

  4. In lines 37 and 38, you are using math.round, but it’s Math.round.

After fixing all that, I tried it and it was working. Let me know how was it for you.

Thank you @2alin for helping out on the forums while I was busy elsewhere, much appreciated.

You are welcome, chris. To help and share is a community’s philosophy :wink:.

@2alin Thank you very much for helping it works. can you suggest any Ideas to master the eventHandlers.

@gnanavelv27, well what it worked for me was to read at least 3 times the Introduction to events lesson over the time, and in practice —when I have doubts of a piece of code doing what it should— I use a lot console.log and it had helped me understand how complicated stuff —like event objects, at that moment— work.

An event is an action that happens with/on an element (being clicked, mouse over it, mouse out of it, key pressed, etc); an event handler or event listener are functions or pieces of code that are waiting for that event to happen, and when it does they execute; and event object are objects (set of properties and methods, with their respective values) that gives you information of a given event, for example the element that the event is imposed on ( which is the target property) and helps you do stuff with that particular element when the event is fired.

Again, embrace console.log, it will help you a lot to understand what’s going on when stuff gets really messy.

@2alin , Thanks a lot mate for the explanation and guidance, Much appreciated.

//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)];
}
// RAW TEXT STRINGS
var temperature = 94 + ’ pounds’;
var weight = 300;

var insertX = [ ‘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’
];

var storyText= 'It was ’ + temperature + ’ farenheit outside, so ’ + xItem +
’ went for a walk. When they got to ’ + yItem +
',they stared in horror for a few moments, then ’ + zItem +
'.thing, but was not surprised ’ + xItem +
’ weighs '+ weight + ‘, and it was a hot day.’;

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

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

if (document.getElementById('uk').checked){
	 weight = Math.round(300) + ' stone';
	temperature = Math.round(94) ;
}

}

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

Hi Ram,

This is a good effort, thanks for trying out the example. Your code has gone a bit wrong in a few places. You are using variables in your string rather than placeholders that could be substituted. This is an ok alternative approach, but you need to make sure that variables you are trying to use are declared before you try to use them in the string.

Also, think about where you are playing other instructions — in this case you are only creating a single silly story, as soon as the app loads, but all the variables are coming up undefined (for reasons touched on above). You want to make it so that a silly story is generated each time the button is pressed, but not before.

You can find our finished version here, for reference:

I put the script tag in the beginning and used the “async” word, it worked.

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

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 / 14) + ' stones';
    var temperature =  Math.round((94 - 32) * 1.8) + ' centigrade';
    newStory = newStory.replace('300 pounds', weight);
    newStory = newStory.replace('94 fahrenheit', temperature);
  }

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

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

This could genarate two different xItem. In the “Hints and tips” part of this lesson, there is a method like this to replace all the strings that have the same value globally:

text.replace(/love/g,‘like’);

So we can add this line for the same random value for xItem:

newStory=newStory.replace(/:insertx:/g,xItem);

Yup, this is true. The reason why I showed the inefficient way in the main example (and only offered the regex version as an alternative lower down) is because I didn’t want to get into a discussion of how regexs work at this stage in a beginner’s course.

2 Likes

After a lot of trial and error / occasionally looking at the source, I’ve finished this assignment, but I’m having issues with the centigrade temp appearing when the UK radio button is selected. I’ve pasted my code below:

thanks for all y’all’s help!

Thanks for submitting your code — it looks great!

I’ve worked out the answer to your question above. My original version had the word “fahrenheit” spelled wrong. Someone fixed it in most places, but in my final version, it was still wrong in the following line:

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

I’ve fixed it now, and updated it on our GitHub repo.

1 Like

i sure do feel silly now in how simple that was. thanks for bringing it to my attention @chrisdavidmills and thank you for all of your hard work.

I think this was my fault really — I should have made sure it was fixed everywhere. At least we worked it out!