Apply Today to our Front End or Back End Programs & check out our scholarships!

Go Back

Building Dynamic User Experiences

Now that we know how to create paths for different outcomes (if statements) and change what the user sees in the browser, let’s combine those big areas of knowledge to build a small app!

For this final section, we will all start with this starter kit!

Warm-Up

The first steps of building our "Guess the Number" game will be very similar to the work you just did!

STEP 1: Write an event listener and a function.

STEP 2: When the function runs, log a message to the user letting them know they clicked the button.

Collect User Input

The one piece of information you don’t yet have is how to collect input from a user. Notice that in the HTML code we have an input tag:

<input type="number">

The input tag is a bit different from others in that it is self-closing, or doesn’t have a closing tag. That’s because there is no content that we would ever need to contain inside of the opening and closing tags!

To collect a numerical value that the user may have typed into a given input element, we can use the following JavaScript code:

var guess = parseInt($('.guess-input').val());
console.log(guess);

Update Your Function

The work you do for this step should take place inside of your function:

STEP 3: Using the code above, create a variable to store the user's guess from the input element. Log it to the console to show the value they typed in. To check that this is working, you'll need to enter a number in the input field and click the button!

That’s a great start! Those console.logs() don’t show for the user though! They are a tool for developers only, but they won’t show on the browser. Instead of using a console.log, let’s show the user the number they typed, in the browser. We can use code like this:

feedback.text(guess);

This line of code says “for the feedback variable, change the text inside of it’s HTML tags to be the value that is stored in the guess variable”.

Final Touches

Think way back to the earlier section on if statements, because this is where they come in:

STEP 4: Instead of notifying your user of the number they typed, write an if statement to compare the user's guess to the secret number.

Depending on if the user's guess is correct or incorrect, change the text of the "feedback" paragraph to a relevant message!

Building Dynamic User Experiences

  • One we have a variety of tools - if statements and event listeners - we can combine them in different way to achieve different outcomes.
  • If you find yourself wondering “is it possible to…”, the answer is most likely “yes”!

Up Next