Shortstuff81000 February 2016

Createing and calling events in Javascript

I'm working on a choose your own adventure game written entirely in HTML and Javascript; I want to create most of my elements entirely in Javascript to create an awesome dynamic game! I am having trouble using events and event listeners. It's a mystery game; after the player chooses their character from a list, they can invite five guests to a party. One of the guests is killed, leaving you to solve the mystery with three suspects.

After you've selected your player, there's another button that says "Select this character!". When this button is clicked, the player creation UI is supposed to be hidden, and a new UI is visible. With the code as it is now, the "StartGame" function is skipped entirely. What am I doing wrong? Any help you can give would be seriously awesome and greatly appreciated!

btnPlayer = document.createElement('button');
btnPlayer.id = 'BTN_btnPlayer';
btnPlayer.type = 'button';
btnPlayer.addEventListener('click', welcomePlayer(), true);
btnPlayer.onclick = welcomePlayer();
btnPlayer.innerHTML = 'Select This Character!';
myDiv.appendChild(btnPlayer);

EDIT I modified my button event properties to look like this:

btnPlayer.addEventListener('click', welcomePlayer, true);
//btnPlayer.onclick = welcomePlayer;

One is commented out because neither has worked. I tried clearing my cache, too. Here is my StartGame() function with the button code excluded. I won't include the "charFirstNames[]" and "charLastNames[]" used to create the choices in my dropdownlist. I have them separated in order to tell a more interesting story; they will eventually be database records when I get the bugs and the basics worked out. I don't think I messed up anything up here, but is it possible that I did? The function is called by the only button coded into the HTML.

function startGame(divName) {
myDiv = document.getElementById('story');

lblPlayer = document.createElem        

Answers


dtanders February 2016

Both of these lines set the onclick handler to the result of calling the welcomePlayer function (see the parens?).

btnPlayer.addEventListener('click', welcomePlayer(), true);
btnPlayer.onclick = welcomePlayer();

You probably mean

btnPlayer.addEventListener('click', welcomePlayer, true);

Post Status

Asked in February 2016
Viewed 2,918 times
Voted 8
Answered 1 times

Search




Leave an answer