Adding dynamic elements to a pop-up window with the use of jQuery's .load() function

When implementing Javascript to create a modal, I have encountered an issue where the close button disappears. The modal opens and loads different HTML files dynamically using the jQuery load() method, but the close button vanishes.

I suspect that the modal is loading first, followed by the load() method, causing the close button to disappear. How can I adjust this so that the close button remains visible?

<nav>
    <a href="data.html">Load Content</a>
    <a href="data_two.html">Load Second</a>
    <a href="data_three.html">Load Third</a>
    <a href="data_four.html">Load Fourth</a>
</nav>
<section id="content">
    <div id="container">
        <p>Hello world This is the data page</p>
    </div>
</section> 
/* modal windoW */
var modal = (function() {
    var $window = $(window);
    var $modal = $('<div class="modal" />');
    var $content = $('<div id="container" />');
    var $close = $('<button role="button" class="modal-  
    close">close</button>');

    $modal.append($content, $close);

    $close.on('click', function(e) {
        e.preventDefault();
        modal.close();
    });

    return {
        center: function() {
            var top = Math.max($window.height() - $modal.outerHeight(), 0) / 2;
            var left = Math.max($window.width() - $modal.outerWidth(), 0) / 2;
            $modal.css({
                top: top + $window.scrollTop(),
                left: left + $window.scrollLeft()
            });
        },
        open: function(settings) {
            $content.empty().append(settings.content);
            $modal.css({
                width: settings.width || 'auto',
                height: settings.height || 'auto'
            }).appendTo('body');
            modal.center();
            $(window).on('resize', modal.center);
        },
        close: function() {
            $content.empty();
            $modal.detach();
            $(window).off('resize', modal.center);
        }
     };
}());

/*initialise modal*/
(function() {
    var $content = $('#container').detach();
    $('a').on('click', function(e) {
        e.preventDefault();
        var page = $(this).attr('href');
        modal.open({
            content: page,  
            width: 340, 
            height: 300
        }); 
        $('.modal').load(page);     
        return false
    })
}());

Answer №1

When you choose the parent element, it will replace all of its content. To prevent this, try selecting the inner div instead.

Modify your code from $('.modal').load(page); to

$('.modal #container').load(page);

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

I am looking to create a route with parameters in Next.js, as well as without any parameters

I am working on a NEXTJS project and utilizing SSR for data fetching. However, I am trying to implement the following scenario: When users land on the "/" route, they should be presented with a random product detail page. But if they search for a specific ...

Navigating Angular.js: finding my way to the endpoint paths

Despite my best efforts and extensive research, I find myself in need of assistance! I have a web application that utilizes node and express on the server side, with Angular on the client side. My issue lies with angular routing. IMPORTANT DETAILS My cur ...

How can I interact with a v-dialog component within a child component in Vue.js using Vuetify?

Exploring Vue.js for the first time and hoping to display a login dialog upon button click. To maintain cleanliness in my code, I shifted the dialog to a child component within a parent component with nested LoginDialog. Below are snippets of the parent co ...

Changing the Div heights in Material UI with grid layout customization

I have a project that requires me to implement material-ui. Is there a way I can adjust the width and height of the div containing the "Sign In With" text (as shown in the first image) to bring the buttons closer to the text? Transformation from this: ht ...

Unexpected response from ajax request

I am struggling to properly handle error messages in my jQuery ajax code. When the fetch array result from my ajax page contains data, I want to display an error message; however, when the array result is empty, I want nothing to happen. Unfortunately, my ...

How to dynamically load a file based on the chosen option value in React

Two select textboxes on my page are named Choose City and Choose District. I also have some files related to cities and districts: // cities.js const cities = { "01": { "name": "City 1", "code": "01" }, ...

What is the best way to dynamically update HTML Select elements using Ajax when other Select elements change?

Currently, I have a search page featuring 7 select dropdowns and 2 textfields. The options in the selects are pulled from a MySQL database. I am looking to implement a functionality where when I make a selection in one of the dropdowns, the other selects ...

Utilizing MongoDB and Express to access collections within a controller

Is there a way to access the collection in the controller using mongodb and express? I came across this code snippet in the mongodb documentation db.getCollection("countries");, but how do you import the database name: db into a controller? serv ...

Preserve the custom hook's return value in the component's state

I am currently facing a challenge in saving a value obtained from a custom hook, which fetches data from the server, into the state of a functional component using useState. This is necessary because I anticipate changes to this value, requiring a rerender ...

Learn the best practices for integrating the options API with the Composition API in Vue3

Using vue3 and vite2 Below is a simple code snippet. The expected behavior is that when the button is clicked, the reactive 'msg' variable should change. It works as expected in development using Vite, but after building for production (Vi ...

Issue: The use of 'ajax' option is restricted for Select2 when connected to an <input> element - Following the update to version 3.1.2

After updating the WooCommerce version to 3.1.2, I encountered an issue while trying to add or edit a variable product. An error message "Uncaught Error: Option 'ajax' is not allowed for Select2 when attached to a element." appears when selecting ...

Create a dynamic process that automatically generates a variety of div elements by using attributes from JSON data

Is there a way to organize the fixtures from this data into separate divs based on the matchday attribute? I've tried using Underscore's groupBy function but I'm unsure how to dynamically distribute the data into individual divs for each re ...

Obtaining select options in jQuery by utilizing the $(this) selector

Looking for a way to loop through and log each option available in a select dropdown box, but struggling with how to use $(this). This is the code I have so far: $('select').each(function(){ $(this).find('options').each(function() ...

What are the different ways you can utilize the `Buffer` feature within Electron?

When attempting to implement gray-matter in an electron application, I encountered the error message utils.js:36 Uncaught ReferenceError: Buffer is not defined. Is there a method or workaround available to utilize Buffer within electron? ...

The background color in the HTML file remains unchanged

Hello everyone, this is my debut post here. I can't seem to figure out why the background color isn't changing for me. Even though I have applied the bg color property, it's not taking effect as expected. <body bgcolor="#f0ffff"> T ...

Left align the CSS menu text next to the menu image

Currently, I have a basic CSS menu that includes background images aligned to the left. My goal is to have the text float to the left of each image as well. <div class='mmenu'><ul><li><a id="li6" class="menu-news" href= "vie ...

Show the cost on the HTML page according to the chosen currency option

I am currently dealing with two primary currencies in my business. The product page is created using HTML. There are 4 products on a single page, and I wish to display two prices for each product based on the selected currency (USD or EUR) without having t ...

Preventing Users from Accessing NodeJS Express Routes: A Guide

Currently, I am working on a React application where I am utilizing Express to handle database queries and other functions. When trying to retrieve data for a specific user through the express routes like so: app.get("/u/:id", function(req, res) { ...

Display loading spinner in Material-UI Table while fetching data

Is it possible to display a Circular progress indicator while waiting for data to populate the table? How can this be accomplished? Currently, the table shows No records to display until the data is retrieved from the server. https://i.stack.imgur.com/Ljq ...

NodeJs: Dealing with package vulnerabilities stemming from dependent npm packages - Tips for resolving the issue

Is there a way to address npm vulnerabilities that are dependent on another package? For instance, I'm encountering an error where the undici package relies on the prismix package. Things I have attempted: Executed npm audit fix Ensured Prismix is u ...