0

I am in a process of writing a hangman game and I bumped into a problem.

The problem is, I have a main.html page where I pick a category to start playing the game. When I click on a category it takes me to the new page. But, before going to the new page I have a function which randomly selects a word and create blank input spaces for the user to start guessing the word. But all this is getting refreshed when it takes me to the new page. I understood what my problem is but I am not sure how to solve it as I am in initial stages of learning javascript and html. I have added the code snippets below. Any help is appreciated. Thank you very much!

    var hangman = {
    	sports: ['football','basketball','tennis','cricket','rugby','ping pong','badminton','hockey'],
    	animals: ['tiger','lion','leopard','wolf','dog','cat','monkey','donkey'],
    	countries: ['india','australia','america','england','new zeland','fiji','singapore']
    };

    var word;
    var category;
    //capture category list on HTML
    //var categoryList = document.getElementById('category-list');
    //var input = document.getElementById('toInput');
    var keys = Object.keys(hangman);

    //Grab the category being chose by the user
    var selectCategory = function() {

    	var categoryList = document.getElementById('category-list');

    	//categoryList.addEventListener('click', function () {


    		if(event.target.tagName === 'LI') {
    			for(var i=0; i<keys.length; i++) {
    				if(keys[i] === event.target.innerHTML.toLowerCase()) {
    					category = keys[i];
    				}
    			}
    			word = hangman[category][Math.floor(Math.random()*hangman[category].length)];
    		}

    		createInput(word);
    	//});
    }

    var createInput = function(arg) {

    var input = document.getElementById('toInput');
    var newItem;

    for(var i=0; i<arg.split('').length; i++) {
    	if(arg.split('')[i] !== ' ') {
    		newItem = document.createElement('input');
    		newItem.className = 'input-item';
    		input.appendChild(newItem);
    		}
    	else {
    		newItem = document.createElement('input');
    		newItem.className = 'empty-item';
    		input.appendChild(newItem);
    	}
    	}

    		window.location.assign("play.html");
    }
    <!DOCTYPE html>
    <html lang="en">
    <head>
    	<meta charset="UTF-8">
    	<title>GoC</title>
    	<link rel="stylesheet" href="style-main.css" href="http://fonts.googleapis.com/css?family=Cinzel+Decorative">
    </head>
    <body>
    	<div class="wrap-main">
    		<h1 class="intro">GAME<span>oF</span>CAKES</h1>
    		<h2 class="tag-line">A CAKE FOR A WINNER!</h2>
    		<ul class="page-links">
    		    <li><a href="player1.html">1 PLAYER</a></li>
    		    <li><a href="player2.html">2 PLAYER</a></li>
    	    </ul>
    	<div id="category">
    		<p>Pick a Category to start..</p>
    		<ul id="category-list" onclick="selectCategory()">
    			<li>Sports</li>
    			<li>Animals</li>
    			<li>Countries</li>
    		</ul>
    	</div>
        </div>
    <script type="text/javascript" src="hangman.js"></script>
    </body>
    </html>

4
  • But, before going to the new page I have a function which randomly selects a word and create blank input spaces for the user to start guessing the word. But all this is getting refreshed put the function in the new page then? Commented Dec 26, 2015 at 22:18
  • You mean write a new javacsript file for the new page? How do I pass on what category the user selected on the first js file to the new one? There are two actions here triggered by a single event which is picking a word from the category and creating a blank input. creating a blank input should happen on next page. Commented Dec 26, 2015 at 22:27
  • You could pass the parameter you need to createInput on next page in window.location(url?p1=value) and on new html you could read it back and do the necessary task with it. @mah3ndra Commented Dec 26, 2015 at 22:28
  • @pratikwebdev - the problem with this is player will see the word he needs to guess in the url. Commented Dec 27, 2015 at 1:10

3 Answers 3

1

This is not so much a problem in need of a solution as it is just poor engineering/structuring of your program. Plan your program around the nature of the environment you're using it in. In web pages when you switch pages the new page runs its code completely fresh.

You'll either have to learn to transfer data between pages (GET vars in the URL might work for you), or don't go to a new page and built it in pure JS. I'd suggest the latter.

Either way, it's a problem with the fundamental structure of how you planned to work your program. You basically need to learn the lesson from it, wipe it and start over with that lesson in mind.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your suggestion. I have already thought of doing it in pure JS but I am interested in learning how to transfer data between pages. I have read enough online but couldn't get my head around it which is why I posted the question.
The first thing you can learn about it is that this is NOT what you'd use it for :)
1

The easiest way is to use Local Storage, which is a key/value store available in the vast majority of browsers, including IE8+.

Save data:

localStorage.setItem('randomWord', 'cat');

Load data:

localStorage.getItem('randomWord');

MDN: Using the Web Storage API

4 Comments

You're right that this can be used...but is this seriously what should be going on? Using local storage just so you can move from the opening screen of a game into the game? It's an X Y problem. The problem comes from the structure of the game. That's what needs to be fixed.
You are certainly correct, there are better tools. However, he's just playing around, not building a huge blockbuster game.
The fact that he's learning and making such a small game are things I personally would consider points AGAINST basically hacking it out with local storage. He learned a valuable lesson about how code works in this environment...so now he goes back and figures out how to do it right. And since it's a tiny game not much time is lost. Much better outcome than learning to hack at X Y problems using local storage :) If this were a blockbuster game with 1000 hours of dev in and and about to launch with money on the line...that's about the only time I'd say "yah, just hack it with local storage".
@Pier-LucGendreau - thanks for your input, I have learnt something new.
0

You aren't going to be passing the state (from the previous page) to the new page when it is rendered. You need to have some way to save the state of the current page (i.e. the randomly generated word) in the current session. This way, you could access the variable from the session when you get to the next page. So for example, in PHP, you can store variables in the session associative array. So in the general example of a login system, you can keep the user logged in across multiple pages by doing something like this:

session_start();
$_SESSION['login'] = "1";
$_SESSION['userName'] = $uname;

This way you would be able to check if the user is logged in across multiple pages. In you case, when you need to check data across multiple pages, this would be an option. Of course, it requires the knowledge of a serverside language like PHP or Python. I would recommend learning one of those.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.