My game starts automatically and I don’t want it to

I followed a tutorial on YouTube about how to make a version of Google’s dino runner game, where you jump the T-Rex over cacti. The version I wound up with is much more simple: he just jumps over a single cactus, over and over again, always at the same interval. Every jump gives a point, and the jump action is tied to W for right now. If you miss a jump, you get a pop-up alert that gives your score and stops the game.

My problem is two-fold:

  1. How can I get the game to start by clicking a button rather than as soon as the page loads and
  2. How can I make clicking the game-over pop-up take the player back to the game’s initial state in which they have to click the start game button to go again?

I’ve tried wrapping the startInterval function in an eventlistener that listens for a click on the startgame button, but all that does is break the collision detection and scoring in the game itself. I’ve gone to w3schools and chatgpt for help on this, as well as a few other resources, but nothing’s worked so far. I feel like the answer is really simple, but I’m just not seeing it.

This is the HTML for the game:

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Dino Game</title>
    <link rel="stylesheet" href="styles.css" />
</head>
<body>
<div class="game">
    <div id="dino"></div>
    <div id="scores">Score:</div>
    <div id="cactus"></div>
    <button id="startgame">Play Game</button>
</div>

<script src="scripts.js"></script>
</body>
</html>

This is the JavaScript:

// JavaScript source code
const dino = document.getElementById("dino");
const cactus = document.getElementById("cactus");
const scoreElement = document.getElementById("scores");


let isAlive;
let score = 0;

document.addEventListener("keydown", function (event) {
    if (event.key === "w") {
        jump();
    }
});

function jump() {
    if (dino.classList != "jump") {
        dino.classList.add("jump");

        setTimeout(function () {
            dino.classList.remove("jump");
        }, 300);
    }
}

isAlive = setInterval(function () {

    // get current dino Y position
    let dinoTop = parseInt(window.getComputedStyle(dino).getPropertyValue("top"));
    console.log(dinoTop);


    // get current cactus X position
    let cactusLeft = parseInt(window.getComputedStyle(cactus).getPropertyValue("left"));
    console.log(cactus);



    // detect collision
    if (cactusLeft < 50 && cactusLeft > 0 && dinoTop >= 750) {
        // collision
        if (!hasJumpedOverCactus) {
            alert("Game over! Your score: " + score);
            clearInterval(isAlive);
        }
    } else if (cactusLeft >= 630 && dinoTop <= 750) {
        // dino jumped over the cactus
        if (!hasJumpedOverCactus) {
            score++;
            scoreElement.textContent = "Score: " + score;
            hasJumpedOverCactus = true;
        }
    } else {
        hasJumpedOverCactus = false; // reset the flag when the cactus is off the screen
    }
}, 5);

And because it might be relevant, here is the CSS styling for the button:

#startgame {
    background-color: dodgerblue;
    border: none;
    color: white;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    position: absolute;
    top: 920px;
    left: 450px;
}

How can I efficiently iterate over all key-value pairs of an object in JavaScript? [closed]

I have an object in JavaScript with multiple key-value pairs, and I need to iterate over all of them to perform some operations. What is the most efficient way to iterate over all key-value pairs of an object in JavaScript?I’ve considered using a for…in loop, Object.keys(), and Object.entries(). Are there any performance differences between these methods, or is there a preferred approach?

Additionally, are there any other methods or libraries that provide better performance or additional functionality for iterating over object properties?

Leaflet.js map.panTo() is not a function, works flawlessly in console

I am building a project that locates IP address with Ipify and Leaflet API’s with VITE.
I couldn’t get the map functions such as (panTo, flyTo and so on) to work so i started a completely clean project to check if i messed something up.
What I have found is that by pasting the leaflet map initialization directly in console – works flawlessly , functions are available.

But when I use the main.js it does not , map.panTo() is not there … What am I missing ?

main.js below – map has been initialized as described in API

let map = L.map("map").setView([51.505, -0.09], 13);

L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png", {
    maxZoom: 19,
    attribution:
        '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
}).addTo(map);

INDEX.HTML below

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap w/ Vite</title>

    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"
        integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin="" />

    <link rel="stylesheet" href="/scss/styles.css">

    <script src="https://unpkg.com/[email protected]/dist/leaflet.js"
        integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>

    <script type="module" src="./js/main.js"></script>
</head>

<body>
    <div class="container py-4 px-3 mx-auto">
        <h1>Hello, Bootstrap and Vite!</h1>
        <button class="btn btn-primary">Primary button</button>
    </div>

    <div id="map" class="bg-body-secondary"></div>
</body>

</html>

I have tried placing the script leaflet.js tags in head, at the end of the body, tried importing in main.js from https://unpkg.com/[email protected]/dist/leaflet.js, with {} or with { map } did not work.

I tried looking for a solution on the web and most of the problems that have occured for other devs are because of declaring map in function which keeps its scope local.

I think mine should be global ? I am completely clueless right now.. Please help

I need functionality of map.panTo to pan the map with results of other API answer .

How I update my node version while using next 14?

I have an issue when I try to create next 14 application.
I have installed already node 20.10.0, and when I try to run my next14 app it show me this error:

screenshot of the problem

Does anyone know how to handle that issue? Will removing node from the computer will solve that problem? if yes, how i delete it properly from my mac?

I’ve tried to update the version of node from the pkg management in the node website, and from nvm.

Calling a function from one javascript file from another

I have a webpage that calls a function from one javascript file on page load. This function then needs to call another function from a different javascript file.

Boiled down to its simplest form, it looks like this:

HTML File

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Website</title>
    <script type="module" src="testing2.js"></script>
    <script type="module" src="testing.js"></script>
</head>

<body onload="testFunc()">
    <div>
    </div>
</body>

JavaScript File 1

import { returnTrue } from './testing2.js';

export function testFunc(){
    console.log(returnTrue())
}

JavaScript File 2

export function returnTrue(){
return true;
}

Running this through a live server throws the following error though:

testing.html:12 Uncaught ReferenceError: testFunc is not defined
at onload (testing.html:12:27)

I know it has something to do with the fact that I’ve turned both the scripts into the type=”module in the HTML file, but I need to do that in order to import the one javascript file to the other.

Any help would be beyond appreciated. I know there’s a good chance that this has been answered already but I’ve run through dozens of different answers on the site and none of them resolve the problem 🙁

Trying to change an HTML attribute with JS, it seems like it should work, but it’s doing nothing

Trying to make a video player with its video being what is after the “?” in the URL.

This is my code in both the iframe page, the video player, and the main page.

player.html, the iframe:

<!DOCTYPE html> 
<html lang="en"> 
<head>  
    <title>Video Player</title> 
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    <link rel="stylesheet" href="style.css">
    
    <script>
        function onload() {
            window.addEventListener('message', function(event){
                acorn = event.data;
                console.log("Message received from the parent: " + event.data);
                console.log("hi " + acorn);
                document.getElementById("vid").setAttribute("src", event.data);
            }
                           );
        }
    </script>
    
</head> 

<body onload="onload()">    
    <!-- Video container -->
    <div class="video-container"> 
        <img src= 
"https://yt3.googleusercontent.com/PyD7VwvJRsHyf0wC-5AxjATC6AhHzKLDlN1UaLM7IvWprWM98K44qNnWLHYJVIUVDC4j_iMU3Q=s176-c-k-c0x00ffffff-no-rj"
            id="video-thumbnail"> 
        <video id="video">
            <source id="vid" src="null"
                type="video/mp4">
        </video> 
        <!-- Controlers continer -->
        <div class="controls"> 
            
        <!-- Left controller div -->
            <div class="left"> 
                <button id="skipminus-10"> 
                    <i class="fa-solid fa-backward"></i> 
                </button> 
                <button id="play-pause"> 
                    <i class="fa-solid fa-play"></i> 
                </button> 
                <button id="skip-10"> 
                    <i class="fa-solid fa-forward"></i> 
                </button> 
            </div> 
            
    <!-- div for progress bar -->
            <div class="video-timer"> 
                <span id="current-time">00:00</span> 
                <span id="separator">/</span> 
                <span id="max-duration">00:00</span> 
            </div> 
            <div class="playback-line"> 
                <div class="progress-bar"></div> 

            </div> 
            
            <!-- Right controller div -->
            <div class="right"> 
                <div class="volume-container"> 
                    <div id="mute"> 
                        <i class="fas fa-volume-up"></i> 
                    </div> 
                    <input type="range"
                        id="volume"
                        min="0"
                        max="1"
                        step="0.01"
                        value="1"> 
                </div> 
            </div> 
        </div> 
    </div>

index.html, the page the user will be viewing:

<!DOCTYPE html> 
<html lang="en">
  <head>
    <link rel="stylesheet" type="text/css" href="../../../style.css">
    <link rel="shortcut icon" type="image/png" href="../../../images/favicon.png">
    <title>Video</title>
  </head>
  <body onload="load()">
    <div class="center">
      <font face = "Verdana" size = "4"><a href="../"><button class="button button">Back</button></a></font>
      <br>
      <br>
      <center>
        <button id="loadvid" class="butt"><font face = "Verdana" size = "4">Load Video</font></button>
        <br>
        <iframe src="player.html" scrolling="no" width="960" height="540"></iframe>
      </center>
      <br>
    </div>
    <script>
      const loadvid = document.getElementById("loadvid");
      loadvid.addEventListener("click", function()
                               {
                       var VID = window.location.search.substring(1);
                                 const iframe = document.querySelector("iframe");
                                 iframe.contentWindow.postMessage(VID);
                                 console.log("Video is located in: " + VID);
                               }
                              );
      function load() {
        var VID = window.location.search.substring(1);
        const iframe = document.querySelector("iframe");
        iframe.contentWindow.postMessage(VID);
        console.log("Video is located in: " + VID)
      }
    </script>
  </body>
</html>

I would very appreciate it if this gets fixed, I’ve been working on this for 3 days straight, if not, more.

React Dynamic MultiSelect

I am new to react and googling multi select is not turning up anything useful. What I currently have is a UI with a multi select, where a user can select a list of states. Now after state selection, a user can select cities based off of the states that they clicked above in a second multiselect. The states part is working, and here is the psuedo code for that piece.


import * as React from "react";
import {MultiSelect}



    type states = [
        states: string[]
        cities: string[]
    ]

    const [results, setStates] = React.useState<states>({
        states: []
        cities:[]
    )};
    
    const allStates = [
        "Utah",
        "Oregon",
        "Wisconsin"
    ]
    const allUtahCities = [
        "Salt Lake",
    ]
    const allOregonCities = [
        "Medford",
        "Portland
    ]

    return(
        <form>
            <MultiSelect
                placeholder = (intl.formatMessage("Please Select a State"))
                options = {allStates.map((x: string) => ({ label: x, value: x}))}
                values = {results.states}
                onItemsChange={(e) => (setField((prev) =>({...prev, states: e? e.map((i) => i.value) : []})))}          
            </MultiSelect>
        </form>
    
    );

What I would like to do, is instead of having a completely separate second multi select with a list of cities, is in the same multi select. If you select Utah, then Salt Lake will appear below it (and checked!) in the same drop down. I feel like I should be able to make an async call to refresh the list, but based off of googling this doesn’t seem possible, so I am turning this query over to the internet incase I am missing something.

If people do not believe the above is possible. Is it possible to list Utah, with Salt Lake below it in the drop down, and if you select Utah, Salt Lake will be selected automatically?

If that is not possible is it possible to have a multi select where all of the options are selected automatically? I feel like this should be possible but I admittedly I haven’t googled that last one.

Best way to check conditional interfaces

export interface YouI {
  from: 'You';
}
export interface MeowGPTI {
  from: 'MeowGPT';
  isPrinted: boolean;
}
export type ConvI = {
  message: string;
  id: string;
} & (YouI | MeowGPTI);

What is the best way of checking the inner conditional type instead of doing this

if("isPrinted" in obj)

Trying to Write a JavaScript input to detect Capslock and display a warning/error message when the capslock key is on [duplicate]

HTML:

    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Detect Capslock</title>
    </head>
    <body>  

    //this is the input area
        <label class="label-button" >Email</label>
        <input id="input" type="text" name="email">  
  

    //this is the error message
        <p id="errormessage" style="display: none; color: red">
        Oops, your email cannot contain any Uppercase!
        </p>  

        <script src="scripts.js"></script>
    </body>

    </html>

This is the HTML code, I am not sure if I should have the inline CSS in the HTML code and still repeat it in the JavaScript code

JavaScript:

  
   const input = document.getElementById("input");

    const errMsg = document.getElementById("errormessage");

    input.addEventListener("keyup", function(event) {

        if (event.getModifierState("Capslock")) {
            errMsg.style.display = "block"; //this line should show the error message when the capslock key is on.
            errMsg.style.color = "red"; //this line shows the color the error message should be in
        } else {
            errMsg.style.display = "none"; //this shows how it should be when the capslock isn't on
            errMsg.style.color = "none";
        }
    }); 

I have an HTML form with an email input field. I’m trying to show an error message in red when the CapsLock key is on, indicating that the email should not contain any uppercase letters. The error message should be hidden when CapsLock is off. The issue is that the error message isn’t displaying when CapsLock is on. Am I correctly using the event listener to detect CapsLock status, and should I duplicate the CSS in JavaScript for styling?

How to pass bool flag from Razor syntax to javascript [duplicate]

I am trying to pass a variable like this:

<script>
var isWhiteLabel = @isWhiteLabel == True ? true : false;

//renders as follows in my Sources tab:
var isWhiteLabel = True == True ? true : false;
//in my output console error: 
//Uncaught ReferenceError: True is not defined
</script>

How can I pass this, to render as javascript variable (true/false)?

AWS API Gateway Custom Domain breaks Authorisation JSWT

I use AWS API Gateway and call it form an Web-App (just jQuery, no Frameworks).

When I call it from code like this, it works:

const sBaseURLNotify= 'https://<my-id>.execute-api.eu-west-1.amazonaws.com/STAGE_default';

$.ajax({
        method: 'PUT',
        crossDomain: true,
        contentType: 'application/json',
        url: this.sBaseURLNotify+'/register_notfication',
        headers: {
          'Authorization': featureLogin.oUser.AccessToken
        },
        data: JSON.stringify({
          oSubscription: JSON.stringify(oSubscription),
        }),
        success: function(data, status) {
          console.log('data', data);
        },
        error: function(xhr, ajaxOptions, thrownError) {
          console.log('thrownError:', thrownError);
          sessionStorage.setItem('oSubscription9', 'none');
          sessionStorage.setItem('iSubscriptiondate', Date.now());
        },
      });

When I instead use the Custom Domain name I set up, it throws the error “Unauthorized”

I just exschange the first line to

const sBaseURLNotify= 'https://stage-api.<my domain name>.de/notification';

The URL seems to be correct, as the Error changes to “”, when I bring in a typo,

const sBaseURLNotify= 'https://stage-api.<my domain name>.de/ntification';

I assume anything in the Custom Domain messes with the “Authorization” header. But I can’t figure out what happens or what I can do about it.

Any suggestions are very welcome!

Cordova plugin purchase not able to register product

plugin-purchase in my application but I’m getting

store.register is not function at cordova.js:232:49

Below are the code`

document.addEventListener('deviceready', function() {
// Initialize the store object
var store = window.store;

if (!store) {
    console.error('Store object not available.');
    return;
}

// Configure the store object
store.register({
    id: 'test_1', // Product ID
    alias: 'product1',              // Product alias (optional)
    type: store.NON_CONSUMABLE      // Product type (e.g., non-consumable)
});

// Add event listeners for purchase events
store.when('test_1').approved(function(purchase) {
    purchase.finish();
});

store.when('test_1').verified(function(purchase) {
    console.log('Purchase verified:', purchase);
});

// Refresh the store to get the latest product data
store.refresh();   }, false);

I have tired every answer but still not able to resolve this issue

Zustand not rerendering

I am a beginner to Zustand. I have a simple use case where there are parent, child components. In the child component, I am using Zustand to update the state, it is getting logged but not re-rendering, could someone please help?

This is the related sandbox – link

Edit: Not sure why sandbox is not loading, I have pasted the code below.

Child.tsx

import { shallow } from "zustand/shallow";
import useStore, { testType } from "./store";

const selector = (state: testType) => ({
  type1: state.type1,
  setValue: state.setValue,
});

export default () => {
  const { type1, setValue } = useStore(selector, shallow);

  return (
    <input
      value={type1.get("0")!.get("label")}
      onChange={(e) => setValue("0", "label", e.target.value)}
    />
  );
};

App.tsx

import Child from "./Child";

export default function Home() {
  return <Child />;
}

store.ts

import create from "zustand";

export type testType = {
  type1: Map<string, Map<string, any>>;
  setValue: (key: string, mapKey: string, mapValue: any) => void;
};

const testMap = new Map([["label", "testValue"]]);
const testMap2 = new Map([["0", testMap]]);

const useStore = create<testType>((set, get) => ({
  type1: testMap2,
  setValue: (key: string, mapKey: string, mapValue: any) => {
    const tempType1 = get().type1;
    const specificType1 = tempType1.get(key);
    specificType1!.set(mapKey, mapValue);
    tempType1.set(key, specificType1!);
    console.log(tempType1);
    set({
      type1: tempType1,
    });
  },
}));

export default useStore;