Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Randomize Output in Javascript On Button Press

Hi everyone!

I'm currently trying to create a 'random name generator' using jQuery. This is what I have so far, the jQuery looks like this

const firstName = ['Tim', 'Sam', 'George', 'Greg']
const lastName = ['Smith', 'Andrews', 'Jones', 'Arnold']
const name = firstName[Math.floor(Math.random() * firstName.length)] + ' ' + lastName[Math.floor(Math.random() * lastName.length)]
const button = document.querySelector('button')

$("button").click(function() {
    $("#nameDiv").text(name)
}); 

which are mapped to this info in HTML:

<div id="nameDiv">
<h1></h1>
</div>
<button>click me</button>

ultimately I'm trying to get the web page to generate a new random name every time the button is pressed, and at this point, the randomized name will appear only once, and then the button basically stops being clickable. Any thoughts?

3 Answers

Steven Parker
Steven Parker
242,822 Points

You're really close, but instead of doing it just once, you want the random picking to happen on each button push.

The easy way to do this is to convert your name assignment into a function, and then call it in the handler:

const firstName = ['Tim', 'Sam', 'George', 'Greg'];
const lastName = ['Smith', 'Andrews', 'Jones', 'Arnold'];
const name = ()=> firstName[Math.floor(Math.random() * firstName.length)] + ' ' + lastName[Math.floor(Math.random() * lastName.length)];
//           ^^^^ convert "name" into a function
const button = document.querySelector('button');

$("button").click(function() {
    $("#nameDiv").text(name());
//                         ^^  add ()'s to call the function
}); 

And it's a "best practice" to end statements with a semicolon. :wink:

So, a couple different things are a bit off. First, you're using const for an object that you want to be dynamic. Best practice is to use let so the browser knows that the object can change (remember, a constant is, well... constant). The next issue goes to scope. Because you're defining name in the global scope, you only randomize the number one time. To make it randomize every time, we're going to have to move the variable into the function.

     //All of this good stuff is defined in the global scope

    const firstName = ['Tim', 'Sam', 'George', 'Greg'],
          lastName = ['Smith', 'Andrews', 'Jones', 'Arnold'],
          button = document.querySelector('button');
    let nameOriginal = firstName[Math.floor(Math.random() * (firstName.length))] + ' ' +     lastName[Math.floor(Math.random() * (lastName.length))];

    $("button").click(function() {
      //All of this stuff is local to the function
      let name = firstName[Math.floor(Math.random() * (firstName.length))] + ' ' + lastName[Math.floor(Math.random() * (lastName.length))];
    // This is basically what you'd need to do if there were no variables, or if you called it in the global scope.
        $("#name1").text(firstName[Math.floor(Math.random() * firstName.length)] + ' ' +
    lastName[Math.floor(Math.random() * lastName.length)]);
    // This is what you had originally. It should work now.
        $("#name2").text(name);
        console.log(nameOriginal);
    });  

Now that that's done, check your console. You'll see that the button function was executing every time, and it was write-in the names to the page, but the nameOriginal object is only changed one time. So, in essence, your solution was working, it just wasn't scoped correctly.

EDIT: Whoops. I forgot to put that I moved your id to the h1 tag in your HTML. It'll make it clearer for anyone looking at your code later, and it helps reduce potential errors with DOM traversal later.

EDIT 2: I'm an idiot and put this as a comment first

Thanks so much!

Steven Parker
Steven Parker
242,822 Points

Jeremy O'Bryan — Glad to help. You can mark a question closed by choosing a "best answer"
And happy coding!