Is there a way to dynamically update the text in an HTML element with a randomly generated value using JavaScript?

Currently, I am working on a coding project where I am attempting to create a flip box that reveals the name of a superhero from an array when clicked by a user. The code pen link provided showcases my progress so far: https://codepen.io/zakero/pen/YmGmwK.

The code functions as expected with the use of alert() in the code pen example. It randomizes and displays a superhero name each time a square is clicked. However, my goal is to have the result displayed after the square is clicked and flipped. Instead of showing "Back", I want it to reveal one of the random superhero names. I've attempted to achieve this by using both .textContent and .innerHTML methods but have been unsuccessful. Here is the snippet of code I've tried:

Javascript:

function setupSquares() {
    for(var i = 0; i < frontSquare.length; i++) {
        frontSquare[i].addEventListener("click", function() {
            var randomNumber = frontSquare[i] = generateRandomNumbers(numbers);
            for(var j = 0; j < superhero.length; j++) {
                var index = superhero.indexOf(superhero[j]);
                if(randomNumber === index){
                    backSquare.textContent = superhero[j];
                }
            }

        });
    }
}
... (remaining content unchanged)

Answer №1

If you want to access the .back of the .front element that was clicked, you can achieve this using the code snippet below:

this.parentNode.querySelector('.back').innerText = superhero[j];

In your scenario, there are some key aspects missing. Firstly, note that backSquare is an array, so you must specify which element within it you wish to update. Instead of using

backSquare.textContent = superhero[j];
, opt for
backSquare[i].innerText = superhero[j]
to target the same i-th element in backSquare as in frontSquare. However, be cautious because this approach might not work due to the use of var i = ... in the loop variable - var does not create a closure over the loop. To rectify this, consider switching from var to let.

For further information, refer to: Closures versus ES6 Let

Alternatively, you can utilize the keyword this which points to the current clicked element. This means that this will represent the element being clicked when used in conjunction with your addEventListener function.

To learn more about this: https://codeburst.io/all-about-this-and-new-keywords-in-javascript-38039f71780c

See a live demonstration here: https://codepen.io/anon/pen/JgbPEK

Answer №2

Another method to achieve the same result is by using this code snippet:

this.closest('.card').querySelector('.back').textContent = superhero[j]

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

Utilize Vue.js to send bound data to a click event

I am currently working with a v-for loop that iterates over data fetched from an API, setting the key as the ID of each object. My goal is to create a click event that captures the v-bind:key value of the clicked element. This will allow me to locate all t ...

What is the best way to keep the menu bar in place as you scroll?

Can someone help me figure out how to keep the menu bar fixed at the top of the page when the user scrolls down? I've tried various methods but haven't had any luck. Any assistance would be greatly appreciated. Here is the CSS code: And here is ...

Is it possible to execute JavaScript code (using Node.js) through AppleScript on MAC OS?

After downloading Node.js for MAC OS from this link: http://nodejs.org/download/ (http://nodejs.org/dist/v0.10.29/node-v0.10.29.pkg), I needed to execute a JavaScript on Google Chrome. To do this, I utilized the following AppleScript code: do shell script ...

Unexpected values being returned by Javascript/jQuery variables

Struggling with understanding scope in JavaScript, like many others before me. It can be quite challenging to navigate through the code at times. I've reviewed previous discussions on this topic, but I'm still having trouble applying it to my spe ...

"Enhance Your Browse experience: Chrome Extension that automatically appends content to pages

I'm currently developing a Chrome extension that detects when a URL on a specific domain changes, and if the URL matches a certain pattern, it will add new HTML content to the webpage. Here is an excerpt from my manifest.json file: { "name": "Ap ...

Problem with Active State of DOM Element

My goal is to create an effect where clicking on a DOM element, specifically a list, will cause the target list to rotate and remain in that position. Describing it can be a bit challenging, so I have provided a visual example of what I'm working on ...

PHP: A guide on validating textboxes with jQuery AJAX

How can I use jQuery AJAX to validate a textbox on focusout? The validation process includes: Sending the value to a PHP page for server-side validation Displaying an alert message based on the validation result I have only impl ...

Is the ClientScriptmanager operational during a partial postback?

After successfully completing an ASP.NET operation, I want to automatically close the browser window. The following code is executed by a button within an Ajax UpdatePanel: Page.ClientScript.RegisterClientScriptBlock(typeof(LeaveApproval), "ShowSuccess", ...

I'm receiving identical results from findOne even when using different IDs

I am currently working on creating a new array of products based on a list of different Ids. However, I have encountered an issue where the same product is being returned for all Ids when using the findOne() method. let wishpro = ['632a5e5rtybdaaf ...

In the realm of JavaScript, removing a DOM element can sometimes feel like an

For my project, I am using JavaScript, DOM, and AJAX to create pages. I am trying to figure out how to check if an element already exists and, if it does, remove it. This is what I have tried: var elementL = document.getElementById('divLogin'); ...

Tips for eliminating repetitive code in JavaScript

I have a jQuery function that deals with elements containing a prefix 'receive' in their class or ID names. Now, I need to duplicate this function for elements with the prefix 'send'. Currently, it looks like this: function onSelectAddr ...

The impact of array splicing on data manipulation

I have a $scope array variable that I'm using to generate tabs on the front end, but I'm struggling with implementing a remove tab function. The code for removing tabs is as follows: function removeTab(index) { $scope.tabs.splice(index, 1); ...

E/AndroidRuntime: CRITICAL ERROR: main --- java code in an android app

I've been working on a map application and I've run into some issues. Can anyone help me figure out what's wrong with my code? ERROR 10-25 01:37:41.296 28673-28673/com.onemap.activities E/AndroidRuntime: FATAL EXCEPTION: main 10-25 01:37:4 ...

Captivating captions for captivating visuals. Pictures don't conform to a linear arrangement

As someone who is new to website creation, I am currently working on adding a CSS effect where a popup-text appears when an image is hovered over. I want to create a row of images for the popups by using an unordered list. However, I'm facing a proble ...

Is there potentially a memory leak in this code? If there is, what steps can be taken to eliminate it?

Recently I inherited a project from my senior colleagues that focused on seamless page reloading using AJAX. The code is filled with numerous functions like this one: function iCreateProblems() { //some random code document.getElement ...

Using AngularJS routing with an Express 4.0 backend API

Recently, I began working on an application utilizing Express 4.0 server. Following a tutorial on scotch.io (http://scotch.io/tutorials/javascript/build-a-restful-api-using-node-and-express-4), I structured the routes to support a backend api serving an An ...

In React, ensure a component's state is preserved when the browser history changes

I recently developed a React application that features a classic layout with a left-side menu, title, footer, and main content section. The side menu includes navigation links structured using components such as <List>, <ListItem>, etc. from th ...

Troubleshooting Problem with Responsive Bootstrap Navbar

I've been working on creating a menubar using Bootstrap where the logo image is centered instead of being on the left side of the bar. However, I'm facing an issue where the right links in the menu go off the screen. When I view the page with a w ...

Contrast between the structure of asp.net button and hyperlinks

I want to transfer the styles of a hyperlink in regular html to an Asp.net button. However, I encountered a strange background issue that is disrupting the appearance of the buttons. Hyperlink: Asp.net Button How can I remove the outline that appears o ...

Vue Single Page Application - invoking methods across all components

I am currently developing a notification feature that can be triggered from any component. It utilizes a straightforward Vuetify v-snackbar. Within App.vue <router-view :key="$route.fullPath"></router-view> <v-snackbar :valu ...