Is it possible to store a randomly generated variable in JavaScript for future reference?

Currently, I am involved in a project that involves generating random variables to create unique scenes. One specific variable is the location of these scenes. My goal is to be able to generate a location with just one button click. Subsequently, by pressing another button, I should be able to generate a new location. Furthermore, upon clicking on the initial button, I would like to retrieve the previously generated location associated with that specific button press.

function locationGenerator()
            {
                    var locations = ["movie", "park", "garden", "home"];
                    var location = locations[Math.floor(Math.random()*locations.length)];
                    
                    document.getElementById('location').innerHTML="<h2>Location</h2>" + location;

Below are the buttons utilized to execute the codes:

<button type="button" onclick="introFunction()">intro</button>
    <button type="button" onclick="midFunction()">mid</button>

To keep track of whether a button has been pressed more than once, I have implemented this code snippet:

function introFunction(){

    if (introClicked == 1){
        document.getElementById('introClicked').innerHTML="<div id=location></div>";
    }
    else{
        document.getElementById('introClicked').innerHTML="<div id=location></div>";
        locationGenerator();
        introClickedFunction();
    }

Additionally, the value of introClicked is updated through this function:

var introClicked = 0;

function introClickedFunction(){
    introClicked = introClicked + 1;
}

Unfortunately, despite implementing the above function, no data is returned upon pressing the button twice.

Answer №1

Store the value generated as a custom field within your <button> tag.

In the code below, the element is passed to the click handler function as event.target. The function checks the gen_locations field. If it's empty, a random value is generated and assigned to it.

window.addEventListener('DOMContentLoaded', _e => {
  const locations = ["movie", "park", "garden", "home"];

  document.getElementById('inhoud-button1').addEventListener('click', inhoudFunction);
  document.getElementById('inhoud-button2').addEventListener('click', inhoudFunction);

  function inhoudFunction(event) {
    let genLocations = event.target.gen_locations;
    if (!genLocations) {
      genLocations = []
      for (let i = 0; i < 2; i++) {
        genLocations.push(locations[Math.floor(Math.random() * locations.length)]);
        event.target.gen_locations = genLocations;
      }
    }
    document.getElementById('inhoud').innerHTML = "<h2>Location</h2>" + JSON.stringify(genLocations);
  }

});
<div id="inhoud"></div>

<button id="inhoud-button1">Inhound 1</button>
<button id="inhoud-button2">Inhound 2</button>

I have improved the code structure by avoiding inline javascript event handlers, which are considered bad practice! :)

Edit: enhanced to demonstrate storing 2 randomly generated values per button

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Breaking down an object containing an internal array and omitting specific keys

I've got this specific object structure: const objBefore: { "id": "3pa99f64-5717-4562-b3fc-2c963f66afa1", "number": "5000", "enabled": true, "classes": [ { ...

Creating a hierarchical menu structure by splitting strings in an array using an algorithm

I have an array of strings in Javascript that look like this: var array = [{ string: 'path1/path2/path3' }, { string: 'path1/path4/path5' }, { string: 'path1/path2/path6' }, { string: 'path10/path7' }, { s ...

Is it possible to encounter the issue of "Context Lost" and "Importing multiple instances" in Three.js?

I am in the process of developing a 3D editor that allows users to manipulate a 3D scene and then view the result by pressing a "play" button. In order to display the output, I am utilizing an iframe. Below is the snippet of my HTML code: <iframe id=&qu ...

How can I retrieve one distinct document for each group based on a shared property value in MongoDB?

I have a database collection set up in MongoDB with a schema like this: var personSchema = new mongoose.Schema({ _id: ObjectId, name: String, // ... alias: String }; (I am using mongoose, but the details are not important). Because I retrieve pe ...

Retrieve an entire item from a single data point

I am currently developing a ticket system and I am looking to implement a feature that allows users to close a ticket, removing it from their account. In my MongoDB array, the structure of the tickets is as follows: { "tickets": [{ &q ...

Using jQuery to create clickable URLs within a rollover div

I am looking to have the div appear on a mouse over effect in the following code. Is there a way for me to input a url based on the data that is passed to it? Anchorage: ["Anchorage", "(555)555-5555"], (This represents the data being posted) AtlanticCit ...

Submitting a PDF document to the server with PHP Laravel through AJAX

Struggling to send a PDF file via AJAX to my server for handling by a PHP script in a Laravel project. The file doesn't seem to be making it to the server. Despite receiving a 200 response in the network, the server is returning 'file not presen ...

Assign the value/text of a div element by using JavaScript/jQuery within a PHP loop

I'm struggling to figure out how to set the value/text of a div using javascript/jquery inside a loop. Can anyone offer some guidance on this issue? Goals: Extract data from a database. Use javascript/jquery to assign the extracted data to an eleme ...

Troubleshooting the issue with utilizing the ng-repeat directive to loop through images in Angular JS

Embarking on my initial website development journey with Java and Spring Boot, I've hit a stumbling block in the front-end realm. Being a newbie, I'm struggling to identify and resolve the issue at hand. Problem title: How do I ...

The JS Fiddle code fails to function properly once it has been downloaded to the local computer

I came across a helpful example fiddle webpage: jsfiddle.net/yijiang/6FLsM/2 After following examples from others, I attempted to download (right click and Save As) using the latest Chrome browser with the following links: jsfiddle.net/yijiang/6FLsM/2/s ...

Determine if the input value is an integer using a custom validator in Angular 2

Looking for a way to validate integer inputs in an Angular2 project? I experimented with using Number(control.value), but it returns 0 for empty fields, which is not ideal. Another method I tried was parseInt(control.value,10), but it ignores spaces. For ...

Only when the condition is satisfied in AngularJS will I include JSON data

I have a JSON file named components.json containing information about various board spaces: {"components": { "boardSpaces": [ {"name":"GO!", "price":0, "position":0, "type":"go"}, {"name":"Mediterranean Avenue", "type": "property", "pr ...

What is the best way to reference a JavaScript or jQuery variable within a PHP variable?

Is it possible to read a javascript or jquery variable through php code? For example: <script> var num = 3; </script> <php? $a = 20; $b = num*$a; // Is this valid? ?> Any thoughts on this? ...

Issue encountered: Next.js version 14, Tesseract.js Error: Module not found .../.next/worker-script/node/index.js'

While working with nextjs 14 and trying to extract text from an image using the tesseract.js node module, I encountered an error where the module was not found. The specific error message I received is as follows: Error: Cannot find module '...(projec ...

Refreshing JWT Authentication in Angular

I am currently following a tutorial on Egghead.io, which can be found here. However, I am adding a MongoDB to fetch my users which is causing me some issues. I have managed to get everything working except for the part where it mentions that the /me route ...

Displaying svg files conditionally in a react native application

I have developed an app specifically for trading dogs. Each dog breed in my app is associated with its own unique svg file, which are all stored in the assets folder (approximately 150 svg files in total). When retrieving post data from the backend, I re ...

Loading tab content on click using jQuery

These tabs have a chrome-like appearance. When the first tab (Facebook) is clicked, it shows Facebook content. Clicking on the second tab (Twitter) displays the content of the first tab. Tabs three, four, and five show their respective contents without any ...

PHP code cannot be outputted to JavaScript due to a syntax error

Although there is a syntax error, the code seems to be working. I am curious about how to make it syntactically correct. The provided code snippet is part of a script that sets up variables for an Ajax call. Depending on the scope, the corresponding varia ...

The functionality of the Sticky state is not effective when it is implemented on a state that contains parameters

It appears that the sticky state feature does not function properly when there are parameters involved. For example: $stateProvider .state('store', { url: '/store', abstract: true, onEnter: ...

Having trouble selecting all checkboxes in the tree using angular2-tree when it first initializes

My goal is to have all checkboxes auto-checked when clicking the "feed data" button, along with loading the data tree. I've attempted using the following code snippet: this.treeComp.treeModel.doForAll((node: TreeNode) => node.setIsSelected(true)); ...