0

I am new to coding, and I am trying to develop some sort of a simple board game.

I have two pages, on the first one, I have a list where one should choose the number of players, then click on a button that will run a function to open a second page and display the number of players.

The problem is when the function is runnig, it seems to stop at window.location, which makes sense. Is there a way that my function could keep running even after the page has changed ?

Below are my two pages and my js code simplified to include only the element that are part of my problem.

function chooseNbrPlayers(){
window.location.href = "page2.html"; 
document.getElementById("demo").innerHTML = document.getElementById("selectNbrPlayers").selectedIndex;
var nbrPlayers =  document.getElementById("selectNbrPlayers").selectedIndex;
    }


<html>
<head>
    <title>page1</title>

    <p><button onclick="chooseNbrPlayers()">Play</button></p>
        <body>
            <form><select id="selectNbrPlayers">
                    <option></option>
                    <option>1 player</option>
                    <option>2 players</option>
                    <option>3 players</option>
                    <option>4 players</option>
                    </select>
            </form>
        </body>
        <script src=script.js></script>
</head>
</html>

<html>
<head>
    <title>page2</title>

    <p>There are <span id="demo"></span> players.</p>

        <script src=script.js></script>
</head>
</html>
8
  • Is there a way my function could keep running, we would need a desired behavior for this. You are routing to a new page. Do you want your script to run there? or do you want to open the URL on next page and keep script running? Commented Feb 18, 2019 at 10:26
  • Do you want to open the URL in new tab? Commented Feb 18, 2019 at 10:28
  • can you upload a fiddle? Commented Feb 18, 2019 at 10:30
  • 1
    Your function just writes output to a specific element and then declares a variable it never uses. Exactly what do you want this to do when the page is unloaded? What output are you expecting to see in an element that's no longer in the browser? Commented Feb 18, 2019 at 10:32
  • Thank you for answering, I'd want to open the url in the same tab. I'd want to run my script on both pages. Basically all I need is to store the number of players in a variable that I can access in the second page. Sorry I really am a beginner and my understanding is very limited :) Commented Feb 18, 2019 at 10:35

1 Answer 1

-2

Your js code retry in any situation, when you redirect at new page. Script.js launch again begin. I think better choice it's a routing. You can write specific scripts for different pages, but i think it's incorrect.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.