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

Encountering a Syntax Error with Haxe while implementing jQueryExtern

Recently delving into Haxe and importing the jQueryExtern library, I encountered an issue while attempting to utilize the following code snippet: new JQuery(".roles:checked").each(function(){ }); This resulted in a compiler error message ...

Troubleshooting why Vue.js isn't updating the DOM with two-way binding

I'm currently utilizing Vue.js for implementing two-way binding. One issue I am facing is with an edit button that should convert a text field into an input field upon clicking. However, the DOM does not update immediately as expected. For instance: ...

Be warned: Babel has detected a duplicate plugin or preset error

Currently, I am enrolled in a React course on Frontend Masters. As part of the course, we were tasked with modifying the Babel config to allow state instantiations like: state = {index: 0} in class components. However, when I executed the command: npm i ...

Click event triggers nested bootstrap collapse

As a beginner in bootstraps and coding, I am currently experimenting with opening the main bootstrap panel using an onclick event that includes nested sub panels. Here is my index.html file containing the panels and the button; <link href="https://m ...

The usage of 'import.meta' is restricted to within modules and cannot be utilized outside of them

I am working on a project that involves Node + Express + Babel + ES6. Within this project, I have the following files: /package.json { "name": "test-backend", "version": "1.0.0", "description": " ...

I am curious to see the number of people who have made their selection

I am currently using JavaScript to alter the text value from "select" to "selected". My next step is to include the selected text in a cart. Can you please provide some guidance? Thank you in advance. PHP CODE : <a class='btn slct' href=&ap ...

Receiving a k6 response that includes a JSON object with a lengthy integer value

During a performance test, I encountered an issue where the response contained items like: {"item":{"id":2733382000000000049}} When parsed using k6's response.json(), it appeared as : {"item":{"id":273338200000 ...

Tips for styling a button upon being clicked

Is there a CSS technique to make a button change color when clicked with the mouse? I am aware of using ':hover' for changing color, but I need something specific to a left mouse click. I want the same functionality as a standard button but with ...

How do I define the specific icon to display on the splash screen for progressive web apps?

In my Progressive Web App (PWA), I have set icons at sizes 144 and 512. Although both icons appear in the application tab in Chrome, the splash screen displays a really small icon (I assume it's using the 144 icon). Is there a method to indicate which ...

Having two AJAX forms on a single page can sometimes cause issues if one is already open when trying to open the other

I have a webpage where users can view and edit data from two forms, Data Part 1 and Data Part 2. Each form has an EDIT button at the top, allowing users to make changes directly on the same page. When a user clicks on the Edit button, an AJAX request is s ...

Stop the form submission until validation is complete

I'm currently working on a form and encountering some validation issues. HTML: <form id="regForm" class="form-group" method="POST" action="signup.php"> <div class="col-md-12"> <h2>Job Pocket</h2> </div> <di ...

What is the process for exporting a plugin from dayjs() in JavaScript?

Currently, I have incorporated the plugin isToday() to enhance the capabilities of dayjs(). Nevertheless, I am uncertain about how to export isToday() in order to utilize it across other files. import isToday from "dayjs/plugin/isToday"; expor ...

When you click on a sublevel in the vertical CSS and JavaScript onclick menu, it disappears automatically

I'm a beginner when it comes to Javascript, and I'm still getting the hang of CSS/HTML. Currently, I am working on creating a vertical menu using CSS and javascript. My goal is to have the sublevels appear on the right side of the menu when someo ...

Issue with Browsersync causing task to malfunction in Gulp 4

Gulp Local v4.0.2, CLI v2.3.0 Browsersync v2.26.13 gulpfile.js: 'use strict' const gulp = require('gulp') const concat = require('gulp-concat') const babel = require('gulp-babel') const uglify ...

The error message encountered is: "TypeError: Unable to access the 'apply' property of an undefined object within the

Currently in the process of developing a node js application with the integration of DHTMLX Scheduler feature on one of the pages. However, my progress is hindered by a recurring issue upon loading the page, resulting in the following error message: TypeE ...

Sending the image's identification number as a parameter to a function and showing the total number

On a static page, I have the following HTML markup: <div class="middle-content"> <div class="white-div"> <div class="like-buttons"> <img id="1" src="up.png" onclick="onClick(true, this.id)" /> &l ...

Error: Oops! The super expression can't be anything other than null or a function in JavaScript/TypeScript

I am facing an issue with class inheritance in my code. I have a class A that extends class B, which in turn extends class C. Whenever I try to create a new instance of class A within a function, I encounter the following error message: Uncaught TypeError: ...

Trouble with closing windows in the in-app browser on Android devices

Is there a method to successfully close the in-app browser? Despite window.close working on iOS devices, it is not effective on Android. I have experimented with alternatives like window.top.close and window.open("", "_self") window.close, but none have ...

Issues with CSS3 height transitions in a specific scenario

Check out this simplified version of my code on CodePen: http://codepen.io/anon/pen/pjZXob I am attempting to create a smooth transition in the height of the .destinationsTopicContent div, from 0 to auto. However, it is nested within a div that has visibi ...

When zooming out, Leaflet displays both tile layers

I'm currently working on integrating two tile layers along with a control for toggling between them. Below is the code snippet I am using: const layer1: L.TileLayer = L.tileLayer('http://{s}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png', { ...