Mah3ndra
Mah3ndra

Reputation: 83

Getting single javascript file work across multiple html pages

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>

Upvotes: 0

Views: 720

Answers (3)

loremIpsum1771
loremIpsum1771

Reputation: 2527

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.

Upvotes: 0

Pier-Luc Gendreau
Pier-Luc Gendreau

Reputation: 13814

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

Upvotes: 1

Jimbo Jonny
Jimbo Jonny

Reputation: 3579

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.

Upvotes: 1

Related Questions