Is it possible to dynamically assign trigger and target divs to bPopup?

On our ColdFusion page, we have a dynamic list of paired divs created using a loop over a query. For example, each pair consists of internshipHandleX and internshipHiddenX:

<div id="internshipHidden#internship.currentrow#" class="hidden pop-up">

We aim to connect these divs as modal windows along with their corresponding triggers. The following code snippet demonstrates our attempt:

for (var row = 1; row <= totalInternships; row ++){
    var thisHandle = "#internshipHandle" + row;
    var thisHidden = "#internshipHidden" + row;
    $(thisHandle).click(function(e){
        e.preventDefault();
        $(thisHidden).bPopup({modalColor:"black"});
    });
}

However, it appears that all the internshipHandle elements are being linked to the last internshipHidden element. What could be causing this issue? Is there a more efficient way to create modal windows from dynamically generated hidden divs within the existing framework without resorting to completely changing to Bootstrap?

Although DreamWeaver discourages placing functions inside loops, some experienced developers advise against heeding its warnings.

Edit: I attempted the same approach with jQueryUI dialog and encountered similar challenges. Any insights or explanations would be greatly appreciated. Thank you!

Answer №1

Greetings from the world of Javascript! You've just stumbled upon a closure in its natural environment.

If you want the row variable to behave as expected, you'll need to pass it within its own scope. This can be achieved using a closure. If you're curious to learn more, delve deeper into this topic, but for now, here's a workaround for your issue:

var totalInternships = 2;

for (var row = 1; row <= totalInternships; row++){
    var bindInternship = function(rowIndex) {
    $("#internshipHandle" + rowIndex).click(function(e){
          e.preventDefault();
          alert('pop-up #' + rowIndex);
          //$("#internshipHidden" + rowIndex).bPopup({modalColor:"black"});
        });
    };
    bindInternship(row);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<button type="button" id="internshipHandle1">pop-up 1</button>
<div id="internshipHidden1" class="hidden pop-up">

<button type="button" id="internshipHandle2">pop-up 2</button>
<div id="internshipHidden2" class="hidden pop-up">

Note: The line for bPopup is commented out. Uncomment it, remove the alert, and you're good to go.

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

Are NPM and Eslint supposed to be this confusing, or am I missing something?

Recently, I've started delving into the world of JS and have been eager to learn more about linting. Following a tutorial, we set up the lint stage in our package.json file. The configuration looks like this: "lint": "./node_modules/.bin/eslint ." U ...

Issue with the useState hook not correctly updating a value

I'm a beginner in the world of react and I'm puzzled by why the title inside the h1 tag updates, but the url within the Image Component remains unchanged? Component Overview import React, { useState, useEffect, useContext } from 'react' ...

"Exploring the density of the xAxis in Highcharts

Currently, I am incorporating Highcharts into my jsp. Typically, when using Highcharts, we are able to create charts with all points evenly spaced along the x-axis. However, in this instance, I am interested in setting the points based on their x-values ...

Combining the value of $(this) to create an identifier name

I am attempting to create a hover effect on an h1 element that triggers the glowing effect on a span element with an id that corresponds to the value of the h1. While I have successfully set up a glowing effect for a sentence, I am struggling to replicate ...

Is there a way to create a customized select handle using CSS?

Is there a way to create a resizable border that appears when a user clicks on the div? And when they move the mouse over it, can the cursor change accordingly? I also want the user to be able to drag the element's border and have the element resize a ...

Generate dynamic routes in Next.js only when needed

I'm currently working on a project using NextJS to create a frontend for a database that contains thousands of products, with the expectation of significant growth. The site/products/ route is functioning well, but I wanted to add a route to view indi ...

Exploring the World of Infinite Scrolling with React.js and Material_ui

I am currently working on a project using react.js As part of this project, I need to implement a board with infinite scroll similar to Facebook I have a specific question regarding this implementation. When scrolling the board and loading more posts li ...

Distance Calculator for Geolocation WatchPosition

I am currently utilizing geolocation to track the user's current location and keep an eye on it using the watchPosition method. Is there a way to determine the distance between the starting position of the user and their current position? Here is the ...

Selecting a range of two months in the datepicker

I am currently utilizing the bootstrap datepicker on my website and I have a specific requirement. I would like to be able to display two months in one input field, showing the current month and the following month. Here are some examples of web pages tha ...

Getting the iframe onload event in an ASP.NET application

I have integrated ReportViewer to display SSRS reports on my .aspx page. However, since the ReportViewer is rendered as an iframe in the browser, I am looking for a way to trigger a JavaScript function every time the iframe loads. Using window.onload w ...

How can I optimize the performance of JS-heavy pages on mobile devices?

As a website owner, I strive to optimize the performance of my site on mobile devices without the need for a separate "mobile-friendly" version or replacing large sections of code. With around 100K of JS code, including jQuery, I am determined to enhance b ...

What is the best way to create an `isHook` function in my code?

Is there a way to determine if a function passed is a React Hook? isHook(useState); // returns true isHook(() => {}); // returns false; I am looking for a method to distinguish whether a function attached to an object property is a hook or not. In cas ...

Is there a way to change a parent's style for only one specific child?

Currently, I am developing an application with a primary layout that utilizes the bootstrap class "container-fluid". <main class="container-fluid"> [....] //a child div where I'd like to remove the parent's padding for this div ...

The function to navigate, 'navTo', is not defined and so it cannot be read

I am trying to create a navigation button in my SAPUI5 application deployed on Fiori _onPageNavButtonPress: function () { var oHistory = History.getInstance(); var sPreviousHash = oHistory.getPreviousHash(); if (sPreviousHash !== ...

Finding the current week using date information from an array of objects in JavaScript

I have an array of objects with a date key, and I am trying to filter out the objects that fall within the current week. How can I achieve this and get the objects from the current week? I attempted to use the filter method, but I believe I need to forma ...

Trouble arises with the jQuery keydown function

Currently, I am encountering an issue with a straightforward jQuery code implementation. In addition to the problem description, I have included the HTML structure below, The current functionality works as expected in setting focus on the input field upo ...

Steps to access arrays that are embedded in a file and are loaded asynchronously

https://gyazo.com/e80eea9f69c0cbb52cc7929d0a46ea2f The name of the object is totalCount. How can I retrieve the count from it? Object.result was my first attempt, but it returned undefined. For my second attempt: var count = totalCount.resu ...

The Google map only displays a quarter of the screen on the left side

Currently, I am working on integrating Google Maps into my project. I have successfully implemented Google Maps services, but I am facing an issue where the map only displays in the top left corner of the container when the page is refreshed. Essentially ...

Understanding the significance of the argument in the context of `express.json({ extended: false})`

Currently, I am in the process of setting up an API using express and encountered this particular line of code: app.use(express.json( { extended: false } )); Although I have referred to the documentation provided by express, I was unable to locate this sp ...

Place a material-ui React component at the center of a footer section

I'm facing a challenge with centering a material-ui Simple Breadcrumbs component within a footer as opposed to having it aligned to the left. Even though I'm new to this, I thought it would be straightforward but I can't seem to figure it ou ...