...

/

Add Game Logic to Our Application

Add Game Logic to Our Application

Learn how to add game logic to the trivia game.

Task 5: Create the welcome header

The welcome header is currently missing, so let’s add that. In the completed game, the header greets the player by the name that they provide on the registration page. We can use Handlebars to generate the header dynamically in the client.

Create the welcome header. Add the following code in the public/js/trivia.js file:

Press + to interact
const urlSearchParams = new URLSearchParams(window.location.search);
const playerName = urlSearchParams.get("playerName");
const mainHeadingTemplate = document.querySelector(
"#main-heading-template"
).innerHTML;
const welcomeHeadingHTML = Handlebars.compile(mainHeadingTemplate);
document.querySelector("main").insertAdjacentHTML(
"afterBegin",
welcomeHeadingHTML({
playerName,
})
);

Let’s break down the syntax above:

  • Line 1: Extract the playerName from the URL search parameters. The player provided this on the registration page.

  • Line 4: Here, target the template that’s embedded as a script tag in the public/trivia.html file.

  • Line 8: Compile the template into HTML by calling Handlebars.compile(), which returns a function.

  • Line 10: Insert welcomeHeadingHTML right after the opening <main> tag

  • Line 12: Invoke the welcomeHeadingHTML function, passing in the playerName data that will be used to render the ...