-1

I want the function home(); to execute only once. When the player chooses their weapon it creates a homepage button every time they click one of three buttons. how can it run once so only one homepage button is created regardless of how many times the game is played again? https://codepen.io/hamisakim/full/XWjVEbx

function home(){ const button = document.createElement("button");
           button.innerHTML = "Homepage";
            button.setAttribute("id",'homebutton')
              const postDiv = document.querySelector('#choices');
                postDiv.appendChild(button);
                

function buttonClick(e) {
  home();
  const choices = ["lapis", "papyrus", "scalpellus"];
  const randomIndex = Math.floor(Math.random() * choices.length);
  computer.currentChoice = choices[randomIndex];
    document.querySelector("#homepageText").innerHTML = '';
    document.querySelector('h3').innerHTML = 'choose below to play again!';
  document.getElementById('choices').removeEventListener('click',null);
Sami Hakim
  • 13
  • 2

3 Answers3

1

Add a check if it has run. A simple boolean

var hasHomeRun = false;
function home(){
  if (hasHomeRun) return;
  hasHomeRun = true;
  ...

Other option would be to check to see if the element exists

function home(){
  if (document.querySelector('#choices')) return;
  ...
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

i think you need this:

window.runHome = false;
const home = function() {
  console.log('run home');
}
const buttonClick = function() {
  if(!window.runHome) {
    window.runHome = 1;
    home();
  }
}
<button type="button" onclick="buttonClick()">Click</button>
MotemaddeN
  • 524
  • 3
  • 9
0

Since your home() functions adds a <button id='homebutton'>, you could use JS to check if that ID is already exists in the DOM

function home() {
    if (!document.getElementById("homebutton")) {
        // Create button, since it's not yet there
    }
}
0stone0
  • 34,288
  • 4
  • 39
  • 64
  • 1
    thank you! this is a nice simple way to do it. – Sami Hakim Dec 29 '20 at 18:51
  • Glad it helped! Please consider [upvoting](https://meta.stackexchange.com/questions/173399/how-can-i-upvote-answers-and-comments) or [accepting](https://meta.stackexchange.com/q/5234/179419) any answers that might have helped you. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. – 0stone0 Dec 29 '20 at 18:53
  • will do. what does the ! on line 2 do? does this make it a "function expression"? – Sami Hakim Dec 29 '20 at 23:21
  • [Take a look at this @SamiHakim](https://stackoverflow.com/questions/19491491/what-does-an-exclamation-mark-before-a-variable-mean-in-javascript) – 0stone0 Dec 29 '20 at 23:58