Issue with Photoswipe pswp class Not Getting Properly Cleared Upon Closing Image

My website has a Photoswipe image gallery from . The issue I'm facing is that the CSS class does not reset or clear after closing the gallery for the second time.

For example, when a user opens item 1, the images are loaded into the picture div via AJAX. Clicking on an image from item 1 opens it in Photoswipe with the following class:


class="pswp pswp--supports-fs pswp--open pswp--animate_opacity pswp--notouch pswp--css_animation pswp--svg pswp--animated-in pswp--visible"

After closing the image from item 1, the class resets to:


class="pswp"

If the user closes item 1 and then opens item 2, the same class is set when opening an image from item 2. However, upon closing the image from item 2, only the attribute changes to:


aria-hidden="true"

but the class remains the same as before, instead of resetting to just "pswp". This causes issues with interaction on the website due to an invisible div/class layer blocking everything else. It's crucial for the class to change back to "pswp."

When populating the picture div using AJAX/JS (an ID is added to the div):


if (i == 0) {
    $('#listing_photos_container').append('<figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject"><a href="' + json[i].image_url + '" itemprop="contentUrl" data-size="512x400" data-index="' + i + '"><img src="' + json[i].image_url + '" height="400" width="600" itemprop="thumbnail" alt="listingPhoto" class="listing-photo"></a></figure>');
} else {
    $('#listing_photos_container').append('<figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject" class="listing-photo-holder"><a href="' + json[i].image_url + '" itemprop="contentUrl" data-size="512x400" data-index="' + i + '"><img src="' + json[i].image_url + '" height="400" width="600" itemprop="thumbnail" alt="listingPhoto" class="listing-photo-holder"></a></figure>');
}

To clear the photo div using JS/JQuery:


$('#listing_photos_container').html('');

There seems to be a double function call issue when users click on a photo to view fullscreen. The listener function code is triggered twice:


$.ajax({
    type: "POST",
    url: 'http://example.com/action?action=photos',
    data: {id: id},
    success: function (data) {
        // Code for styling etc.
        // PhotoSwipe initialization and configuration
    }
});

Answer №1

If you've already resolved this issue, great! But just in case someone else encounters the same problem...

The issue may arise if you inadvertently open the gallery multiple times without properly closing it. It's possible that there are multiple click handlers registered to open the gallery or that the event is triggered twice for some reason.

This problem occurs because the current class name of the pswp element is cached during initialization and then restored on destruction. If a second opening happens without a proper destroy call, _initialClassName will be set as

class="pswp pswp--supports-fs pswp--open pswp--animate_opacity pswp--notouch pswp--css_animation pswp--svg pswp--animated-in pswp--visible"
, which results in the issue you're experiencing.

Check line 776 of photoswipe.js where initialclass is set

_initalClassName = template.className;

Set a breakpoint in your browser to track if this is being called multiple times upon opening.

Inspect the destroy function starting from line 942 onward

destroy: function() {
    _shout('destroy');

Put a breakpoint in your browser to ensure it is executed every time the open function is called.

Solution:

The core issue lies in adding a click handler to open photoswipe when loading images into #listing_photos_container and failing to unbind this handler when closing the popup. Therefore, each time you reopen the popup, a new click handler is added on top of the existing ones.

To resolve this, simply unbind the click handler using $(".picture").off('click'); within your closeListing() function.

Answer №2

One easy solution is to add .off('click') before each .on('click').

For instance:

$('button#submit-form').off('click').on('click', function() {
    // submit form logic goes here
});

Answer №3

I encountered a similar issue where defining lightBox as a global variable solved the problem. Make sure to set it to null when destroying it. Additionally, before initializing lightBox in any function, check if it has already been defined and if so, exit the function early.

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

Monitor modifications to an <input type="text"> element as its value is updated dynamically through JQuery from the server side

I am struggling with detecting when the value of an input field changes after it has been set by clicking a button. I have tried various events but can't seem to find the right one. <!DOCTYPE html> <html> <head> <script src=" ...

Having trouble with a dropdown menu that allows for multi-select options?

var expanded = false; function showCheckboxes() { var checkboxes = document.getElementById("checkboxes"); if (!expanded) { checkboxes.style.display = "block"; expanded = true; } else { checkboxes.style.display = "none"; expanded = fa ...

Creating a versatile PHP script capable of managing multiple forms

Each time I develop a website for a client, I find myself in the same cycle of writing form HTML and then creating a PHP script to manage the data. Dealing with lengthy forms or multiple forms can make the process messy. Before diving into crafting a dyna ...

Bringing the value from the codebehind to the jquery function on the client side

Here is the code snippet from my asp.net web application's code behind where I have integrated another web service: [WebMethod] public static string GetData(string name) { WEBSERVICE.Service1 Client = new Service1(); string Nam ...

Is there an array containing unique DateTime strings?

I am dealing with an Array<object> containing n objects of a specific type. { name: 'random', startDate: '2017-11-10 09:00', endDate: '2017-11-23 11:00' } My goal is to filter this array before rendering the resu ...

Switching Formview mode using javascript

Currently, I have a formview on my website and I am looking to change the formview mode using JavaScript. Specifically, I want the formview to switch between insert mode and edit mode based on different interactions with buttons. I have a repeater on my p ...

Transforming a Division into a Dropdown Menu

I currently have 2 sets of Div Tags structured like this: <div id="sortlocation" class="facetsearch"> <div class="facetlist"> <div id="facet_20" class="facetitem">Adambakkam <span class="facetitemcount">(15)</span> ...

What does Angular classify as a watcher?

What qualifies as "watchers" within Angular? Are watchers the only type of monitoring mechanism, or do other Angular elements like ngModel also serve as watchers? Am I overlooking something crucial? For example, do watchers play a role in enabling directi ...

The JQuery .replaceWith method exclusively offers unprocessed HTML content

I'm experiencing a minor issue with my ajax response where it returns raw html and does not execute any scripts, resulting in the jquery ui scripts not being executed. Here are some details: I am currently working with ASP.NET MVC and I need to comm ...

Tips for showcasing the chosen option from an autocomplete input field in a React application

Currently learning React and working on a search feature for a multi-form application. The goal is to allow users to search for a student by first name, last name, or student ID using an autocomplete text field. The options for the autocomplete text field ...

Having issues with passing data correctly in a jQuery AJAX PHP login system

I am encountering a Failure object Object notification. Despite reviewing various examples, I am unable to pinpoint the error. My suspicion is that my AJAX setup is not configured correctly. The PHP code seems to be in order as it interacts with a local da ...

React: I am looking to incorporate two API calls within a single function

I am currently learning ReactJS and focusing on implementing pagination. My goal is to fetch page data from a server using an API, with Loopback being the tool for API integration. The initial setup involves displaying a list of 10 entries on the first pag ...

jQuery not displaying Div elements as expected

After experimenting with the Coverflow technique and adapting it to work with a div, I have encountered a slight issue. Below is the HTML code I am using: <html> <head> <meta http-equiv="Content-type" content="text/html; ...

Is there a way for a DOMWindow popup to automatically resize to fit its

Currently exploring JQuery and learning on the fly, I'm wondering if there's a method to automatically adjust the size of a DOM window based on its content? I've successfully modified the parameters to accept % width and height instead of p ...

What is the best way to use jQuery and "Long Polling" to dynamically update HTML pages on an Indy HTTP server?

After thoroughly reviewing the content in the article Simple Long Polling Example with JavaScript and jQuery, I came across a paragraph titled "Long Polling - An Efficient Server-Push Technique," which discusses the Long Polling technique merges the eff ...

Non-clickable image

My social media page icons are not hyperlinked, and I can't figure out why. I've surrounded them with the href attribute, but for some reason, it's not working. Can anyone provide assistance? Here is the HTML code: <!DOCTYPE html> ...

Automatically update div content using jQuery including an AJAX request for loading

I have successfully implemented a method for loading output from now_playing.php (shoutcast now playing content) using a jQuery include ajax call, as recommended in this answer on Stack Overflow. Here is my code: <script> $(function(){ $("#now_ ...

Tips for positioning a navigation bar in the center for various screen resolutions

After hours of searching, I still can't find a solution to my problem. I'm new to this, and on my main monitor, everything looks centered just fine. 1920x1080: View larger image But on my 1280x1024 monitor: View smaller image As you can see, i ...

Encountering a 500 Internal Server error due to PHP header location redirect

Whenever the script below reaches the header ('location:php_email_thankyou.php'), I keep encountering a 500 Internal Server Error. I'm perplexed as to what is triggering this issue. Interestingly, I have tried moving the header expression b ...

Use jQuery to smoothly scroll a div

I created a container using a <div> element which is divided into 3 inner divs. The first two inner divs are meant to serve as previous and next buttons, with ids of prev and next respectively. At the bottom, there are 3 more inner divs, each with un ...