When attempting to submit data, the Magnific Popup page is restored to its default format

I am facing an issue with my Magnific Popup page:

function dataLink(){
    $.magnificPopup.open({
        items: {
            src: 'datapage.html',
            type: 'ajax'
        },
        closeOnContentClick : false, 
        closeOnBgClick :true,
        showCloseBtn: false,
        enableEscapeKey : false,
        callbacks: {
            open: function(){
                $.magnificPopup.instance.wrap[0].addEventListener('focus', mpTable);
            },
            close: function(){
                $.magnificPopup.instance.wrap[0].removeEventListener('focus', mpTable);
            },
        }
    });
}

The datapage.html contains two tables that are initially hidden or shown based on the context (with data1table being visible and data2table hidden):

<div class="white-popup">
  <table id="data1table" class="table1">    
  </table>
  <table id="data2table" class="table2">
  </table>    
</div> 

There is a button within table1 that switches the visibility to table2. In table2, there is also another button that triggers a JavaScript function to check and send data:

<input onclick="dataCheck()" type="button" value="Check Data" />

This function is defined as follows:

function dataCheck(){
    if(datacheck[0]==false || datacheck[1]==false){
        alert("Please enter data in all fields correctly.");
    } else{
        $.ajax({
            url: 'dataconfirm.php',
            type: "POST",
            async: false,
            data: {

            },
            dataType: 'json',
            success: function(data){
                alert("Thank you!");
                localdata=data;
                $.magnificPopup.close();
            }
        });
    };
}

My challenge arises when clicking the button to execute dataCheck(); it reverts back to showing table1 without running the function. However, upon clicking the button a second time to display table2, the functionality of dataCheck() works as expected. I'm puzzled by this behavior and would appreciate any insights or suggestions to address this issue. Thank you!

Answer №1

After some troubleshooting, I finally identified the root cause of the issue. While working with callbacks in my code, I followed recommendations from the creator of Magnific Popup and others to add an EventListener for manipulating DOM elements. This was necessary because the open callback is triggered before the elements are created, leading to errors when attempting changes directly within this callback due to non-existent elements. You can find more information on this topic in my own answer, as it seems that many others have faced similar challenges related to the absence of an afterload callback: Magnific popup: Get current element in callback

For further insight, check out:

https://github.com/dimsemenov/Magnific-Popup/pull/634

https://github.com/dimsemenov/Magnific-Popup/issues/632

During experimentation, I discovered that using focus as the event in the EventListener caused unexpected behavior when clicking a second button, resulting in the page being refocused and triggering the EventListener. To address this, I changed the event type to onload:

$.magnificPopup.instance.wrap[0].addEventListener('onload', mpTable);

This approach somewhat resolved the issue but introduced new complications. The most effective solution was modifying the mpTable function to ensure it only executed once:

function mpTable(e){

    e.target.removeEventListener(e.type, arguments.callee);

    //other actions performed by the function

}

I share this experience in the hope that it can assist someone facing similar challenges in the future!

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

Imitation of three-dimensional camera rotation

I've been exploring the realm of creating 3D games using JavaScript and HTML's 2D canvas. I recently came across a helpful tutorial that guided me in setting up a basic interactive scene. Now, I'm facing a challenge in implementing the func ...

Setting the state of a nested array within an array of objects in React

this is the current state of my app this.state = { notifications: [{ from: { id: someid, name: somename }, message: [somemessage] }, {..}, {..}, ] } If a n ...

Challenges when utilizing the command "npm install" within a programmatic context

I'm really excited about the potential of using "npm programmatically," but I've hit a roadblock. The function "npm.load" doesn't seem to be triggering for me. None of the console logs inside of my "npm.load" or "npm.commands.install" functi ...

Receive information from a form and store it in an array

Struggling to figure out how to convert this into an array. I'm having trouble grasping the concept of taking input from a form and storing it in an array. In my project instructions, it clearly states: Do NOT save the input in variables and then tra ...

JavaScript regular expressions: filtering out results from the output

I'm trying to extract a specific number from a dynamically added string. The text looks like this: nisi non text600 elit, where 600 is the number I need to retrieve. Is there a way to achieve this without replacing the word text? var str = ('nis ...

tips for obtaining the highest value among multiple keys within an array

How can I find the maximum value among multiple keys in an array? I previously attempted to find the maximum values for just three keys. getMaxValuefromkeys(values: any[], key1: string, key2: string, key3: string) { var val1 = Math.max.apply(Math, v ...

How can I make the top two divs stay fixed as I scroll down, and then reset back to their initial position when scrolled

Hey there, I'm looking to have a div stay fixed after scrolling within its parent div. <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12"> <div class="fw ofndr-box"> <div class="ofndr-box-half add-here"> <a href="#! ...

"Ensuring that every" within handlebars js

I have been exploring handlebars.js (hbs) and although I haven't mastered it yet, I am curious to know if there is an equivalent to the following code: {{#if all source}} If not, how can I create a similar functionality using handlebars.js? ...

What is the purpose of defining the initialState in Redux?

As per the Redux documentation, it is considered a best practice to establish an initialState for your reducer. However, maintaining this initialState can become challenging when the state relies on data from an API response, leading to discrepancies betwe ...

Prevent certain images from loading by blocking them

I am trying to create an extension that blocks two specific images from loading. Initially, I attempted to achieve this by using the following code in the content.js file: $("#rated-image").remove(); //id of one image $(".blur-mask").remove(); //class of ...

I'm curious about using NextJS to fetch an API with a specific router ID. Can anyone provide guidance on how to achieve this and then render the data as HTML?

Greetings! I am currently coding in NextJS and working on a user page that fetches user-specific information from an API. My goal is to extract the ID query from the URL and use it to make an API request. The API endpoint follows this structure: /Users/{i ...

Determining the file path in HTML5

Can anyone help me with retrieving the file path using html5 javascript once a user selects a file? I require the file path for a specific scenario: In this case, the user uploads a file and pauses it (currently only supported by Mozilla browsers), then c ...

Trigger an event when the menu is outside the viewport and then lock the menu to the top of the viewport

I am trying to create a menu element that remains fixed at the top of the browser viewport as the user scrolls, ensuring it is always visible. In my webpage layout, the menu sits below some text in the header initially. Once the user scrolls past the heade ...

The latest bug fix and update in Bootstrap 4.5.2 now includes an updated version of Popper.js. Make sure to use the

Hello fellow developers, I am currently working with npm bootstrap version 4.5.2 and above. However, I am facing an issue with the compatibility of @popperjs/core. If anyone can assist me in resolving the bootstrap.js error temporarily, specifically re ...

Turning On/Off Input According to Selection (Using jQuery)

<select name="region" class="selection" id="region"> <option value="choice">Choice</option> <option value="another">Another</option> </select> <input type="text" name="territory" class="textfield" id="territo ...

Trigger a popup notification with JavaScript when

Check out this snippet of code: <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/ ...

Increment and decrement the like count on fa-heart multiple times

Is there a way to increment the count of a fa-heart value on click and decrement it on the second click? The issue I'm facing is that I have multiple fa-heart elements on the same page, making it challenging to increment or decrement the clicked fa-h ...

Enhancing IntelliJ IDEA's autocomplete functionality with JavaScript libraries

Is there a way to add my custom JavaScript library to IntelliJ IDEA 10.5 or 11 for autocomplete functionality? I want to specify that IDEA should recognize and suggest auto-completions for objects from my library. While it sometimes works automatically, ...

Tips for identifying a pair of numbers (with varying ranges) in which one number must be present at all times

I am currently trying to understand the regex I have implemented in Angular 2 using Typescript: /[0-5]?[0-9]?/ Surprisingly, this regular expression works flawlessly to match any valid minute from 1 to 59, even though it seems like an empty string would ...

sw-precache-webpack-plugin for webpack's default service worker template

When utilizing the sw-precache-webpack-plugin to create a service worker for my project, I've noticed that while all my fonts, js, and css files are stored in the cache storage, the index/html file is missing. This has resulted in it not functioning p ...