JavaScript loop not functioning properly to show modals when button is clicked

I successfully created a Javascript function to display a modal on button click, but I realized that I would have to manually repeat the code 56 times. Instead, I attempted to write a loop to automate this process, but unfortunately, the new function is not functioning as intended and I am unsure of the reason behind it.

The initial working function:

var target = document.getElementById('show1');
var currentOpacity = 0;
$(document).ready(function () {
  $("#hide1").click(function () {
    $("#details1").hide();
    target.style.opacity = currentOpacity + 1;
  });
  $("#show1").click(function () {
    $("#details1").show();
    target.style.opacity = currentOpacity - 1;
  });
});

Instead of repeating the above code block an additional 56 times:

var target = document.getElementById('show1');
var currentOpacity = 0;
$(document).ready(function () {
  $("#hide1").click(function () {
    $("#details1").hide();
    target.style.opacity = currentOpacity + 1;
  });
  $("#show1").click(function () {
    $("#details1").show();
    target.style.opacity = currentOpacity - 1;
  });
});
var target2 = document.getElementById('show2');
$(document).ready(function () {
  $("#hide2").click(function () {
    $("#details2").hide();
    target2.style.opacity = currentOpacity + 1;
  });
  $("#show2").click(function () {
    $("#details2").show();
    target2.style.opacity = currentOpacity - 1;
  });
});

would be laborious, so I tried using a loop:

const elements = [];
for (let i = 1; i <= 56; i++) {
$(document).ready(function () {
  document.getElementById('hide'+i).addEventListener('click',function ()
{
document.getElementById('details'+i).hide();
document.getElementById('show'+i).style.opacity = currentOpacity + 1; });
document.getElementById('show'+i).addEventListener('click',function () {
document.getElementById('details'+i).show();
document.getElementById('show'+i).style.opacity = currentOpacity - 1; });
});
}

However, the loop approach is not yielding the expected results. Can anyone provide insight into why this might be happening?

Answer №1

Initially, let's address the issue at hand

for (let j = 1; j <= 56; j++) {
    $(document).ready(function () {

appears to be incorrect.... it might be more appropriate like this

$(document).ready(function () {
    for (var j = 1; j <= 56; 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

Access a component from the @ViewChild without resorting to nativeElement

Is there a way to access the underlying div element using a @ViewChild? I have attempted the following approaches without success: ElementRef.prototype.nativeElement -- returns ElementRef HTMLDivElement -- returns undefined ElementRef -- returns ElementRe ...

The designated origin in JavaScript is not displaying in the Django template

Sorry for the possibly silly question, but as I delve into Javascript and Django, I'm struggling with a specific issue. Despite spending hours on it, I can't seem to figure out why my image isn't displaying in my Django HTML template. Here ...

Access the menu featuring a pair of distinct buttons

I have a simple dropdown menu that can be triggered by clicking on the icon NewIcon in DropdownMenu.Trigger. Implementing this dropdown menu is straightforward, as I am using the radix library () <DropdownMenu.Root open={isOpen} onOpenChange={setIsOpen ...

Display HTML content retrieved from a string saved in a React database

I am currently in the process of creating a React page and facing a challenge with incorporating HTML content from a RTDB that has been styled using "use styles". Here is an example of the styling: import { makeStyles } from '@material-ui/core/style ...

Executing server side code using client data in next.jsIn next.js, executing server side code with data

Is there a way to extract metadata from a URL that is provided by the user in my Next.js application? To achieve this, I am utilizing a tool called metadata-scraper. However, upon submission of the form by the user, my application encounters an error: ...

Encountering difficulties in running bootstrap on nodejs

As a beginner in node.js and bootstrap, I am eager to create my own personal website, so I found some tutorials to help me get started. After downloading bootstrap 2.0.2 and unzipping it, I organized the files by placing bootstrap and bootstrap-responsive ...

Troubleshooting custom buttons error when using carousel in Nuxt app: "Flickity is not defined"

I am attempting to connect my own personalized buttons to a flickity carousel within a nuxt application. Within my carousel component, the following code is present: <template> <ClientOnly> <Flickity ref="flickit ...

How can an array be concatenated using tabs?

I am currently in the process of integrating with an old system that requires a value to be sent via a GET request as a tab delimited string. I have my data stored in an array, but I am facing difficulty when attempting to properly format it using the join ...

What's the Deal with Blank Square Brackets in JavaScript?

While browsing through , I stumbled upon this code snippet: useEffect(() => { const interval = setInterval(() => { console.log('This will run every second!'); }, 1000); return () => clearInterval(interval); }, []); I am intri ...

The radio button's on click event necessitates a double click

At the heart of my issue are two radio buttons within a form. One triggers a registration form for new users, while the other allows already registered users to sign in. To aid with validation, I've integrated jVal form validation. The problem arises ...

Tips for accessing a RESTful web service using an AJAX call

I am having trouble calling my REST web service using AJAX. The URL for my service is ''. I can successfully call this service from a REST client in the Firefox browser, but when I try to call it from AJAX, I get an error. Here is my AJAX call : ...

Leveraging the power of Javascript Proxy and the spread syntax, along with the trust

While experimenting with Proxy objects and exploring their interaction with spread syntax and de-structuring, I encountered an unusual behavior: const obj = { origAttr: 'hi' } const handler = { get(target, prop) { console.log(prop); ...

Information vanishes upon scrolling and toggling on the page

While working on creating a website, I came across a great template and decided to use it as inspiration. You can check out the template here. However, during the process, I encountered a common UI bug. When a user scrolls down the page, clicks on the "X ...

Creating unique styles for components based on props in styled MUI: A comprehensive guide

One challenge I am facing is customizing the appearance of my component based on props, such as the "variant" prop using the 'styled' function. Here is an example code snippet: import { styled } from '@mui/material/styles'; const Remov ...

The connection between IE11 and Google is not functioning properly

Currently, I am working on an IE11 extension, which involves using an XMLHttpRequest (GET) to retrieve data from Google's settings page. The code is executed on the extension's background page. Here are the specific details I am including in the ...

What resources are available for creating the framework of a TypeScript package in DefinitelyTyped?

I am interested in making contributions to by providing new types similar to what can be found on https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types. I believe there must be a way to create a package from scratch or get started. I have ...

Incorporating click functionality in React for a to-do list feature

I've recently developed a task management application using React. However, I've encountered a couple of issues with the functionality. I am unable to mark tasks as completed by simply clicking on them, and the option to clear completed tasks by ...

Using a TCP server to transfer and store files with node.js

I am managing multiple devices that are continuously sending messages to a TCP Server built in node. The primary purpose of this TCP server is to route certain messages to redis for further processing by another application. I have created a basic server ...

Acceptable choices for inclusion in .on when utilized as a proxy

According to the documentation on jQuery, it is stated that a selector needs to be passed in as a string to the .on() method. For example: $('#someEl').on('click', '.clickable', function() { /* ... */ }); Interestingly enoug ...

Error: Property ID was not followed by a colon

There is a Syntax Error: missing : after property id near '<img src="loading.gif" />';` <script> $(document).ready(function() { $("#client").on("change", function() { var clientid=$("#client").val(); ...