Photoswipe pswp class Not Clearing After Closing Image - javascript

I have a Photoswipe (http://photoswipe.com) image gallery on my site, and the css class is not resetting/clearing to remove the view after I close a gallery for the second time.
ex.
User opens item 1, AJAX populates the figure(s) into the picture div.
User clicks an image from item 1 and Photoswipe opens the image properly (setting 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"
User closes the image from item 1, class resets as normal:
class="pswp"
User closes item 1 and JS/JQuery clears all html in picture div. User opens item 2, AJAX populates the figure into the picture div. User clicks an image from item 2 and Photoswipe opens the image properly setting the same class as before.
class="pswp pswp--supports-fs pswp--open pswp--animate_opacity pswp--notouch pswp--css_animation pswp--svg pswp--animated-in pswp--visible"
This is where the problem occurs. User closes the image from item 2 and the only thing that changes is:
aria-hidden="true"
but the class does not clear, it remains:
class="pswp pswp--supports-fs pswp--open pswp--animate_opacity pswp--notouch pswp--css_animation pswp--svg pswp--animated-in pswp--visible"
when it should change to:
class="pswp"
This disables all interaction on the website since there is an invisible div/class on top of everything. The class needs to be changed back to pswp somehow.
AJAX/JS To Populate picture div (I added an id to the div):
if (i == 0) {
$('#listing_photos_container').append('<figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject"><img src="' + json[i].image_url + '" height="400" width="600" itemprop="thumbnail" alt="listingPhoto" class="listing-photo"></figure>');
} else {
$('#listing_photos_container').append('<figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject" class="listing-photo-holder"><img src="' + json[i].image_url + '" height="400" width="600" itemprop="thumbnail" alt="listingPhoto" class="listing-photo-holder"></figure>');
}
JS/JQuery to clear photo div:
$('#listing_photos_container').html('');
EDIT: The click listener function is running twice when a users clicks the photo to bring full screen. This is the code for the listener:
$.ajax({
type: "POST",
url: 'http://example.com/action?action=photos',
data: {id: id},
success: function (data) {
console.log('API Call - Photos');
json = JSON.parse(data);
$('#listing_photos_container').html('');
for (var i = 0; i < json.length; i++) {
// Styling code here
}
$('#list_header').html(
(function($) {
$('.picture').each( function() {
var $pic = $(this),
getItems = function() {
var items = [];
$pic.find('a').each(function() {
var $href = $(this).attr('href'),
$size = $(this).data('size').split('x'),
$width = $size[0],$height = $size[1];
var item = {
src : $href,
w : $width,
h : $height
}
items.push(item);
});
return items;
}
var items = getItems();
console.log('Items for PSWP' + items);
alert('Alert Point 1'); // This is called once, (as it should).
var $pswp = $('.pswp')[0];
$pic.on('click', 'figure', function(event) {
// This block is called twice..
alert('Click Funct');
event.preventDefault();
var $index = $(this).index();
var options = {
index: $index,
bgOpacity: 0.7,
showHideOpacity: true
}
// Initialize PhotoSwipe
alert('Setting new PhotoSwipe');
var lightBox = new PhotoSwipe($pswp, PhotoSwipeUI_Default, items, options);
lightBox.init();
}); // End $pic.on
});// End .picture each
})(jQuery)
); // End list_header.html
} // End AJAX Success
}); // End AJAX

You may have already fixed this, but in case someone else falls upon this.
This can happen if you trigger opening the gallery more than once without closing it. It may be that you have registered multiple click handlers to open the gallery or for some reason the event is being fired twice.
It happens because in the init function the current class name of the pswp element is retrieved and cached, then on destroy the class name is restored. When the second open occurs without destroy being called _initialClassName will be set to class="pswp pswp--supports-fs pswp--open pswp--animate_opacity pswp--notouch pswp--css_animation pswp--svg pswp--animated-in pswp--visible" as your are seeing
Line 776 of photoswipe.js where initialclass is set
_initalClassName = template.className;
Breakpoint this in your browser to see if it is called multiple times when opening
Line 942 onwards destroy function
destroy: function() {
_shout('destroy');
Breakpoint this in your browser to ensure it is being called for every time open is called
Final Solution
The problem is that when opening the popup and loading the images you are filling #listing_photos_container with your photos, then adding a click handler to open photoswipe. This click handler is added to the top element, so will remain when the popup is closed, then the next time it is opened a new click handler will be added.
To fix this you just need to unbind the click handler when closing the popup, you can do this with $(".picture").off('click'); somewhere inside your closeListing() function

It's quite simple, before every .click(...) you need to write .unbind('click').
Example:
$('a#open-photoswipe').unbind('click').click(function() {
// open photoswipe here
});

Was having similar problem - just define lightBox as global variable. And on destroy define it as null. And in beginning of function where You initialize lightBox just check if lighBox is already defined, then do return.

Related

Replace a "Click to load more" into a Scroll to load more

Currently, my client's website has a "Load more" button, linked to the Shutterstock API to load more photos everytime you click on that button.
My client asked to change this into "When the user scrolls down, it loads automatically more images".
So what I thought, since I'm not an experienced coder, is to add a function linked with window.scroll that would trigger a click on that button once you reach the top of that button, using the following code:
$(window).scroll(function() {
var top_of_element = $("#load_more_images").offset().top;
var bottom_of_element = $("#load_more_images").offset().top + $("#load_more_images").outerHeight();
var bottom_of_screen = $(window).scrollTop() + window.innerHeight;
var top_of_screen = $(window).scrollTop();
if((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
$("#load_more_images").trigger("click");
}
else {
// The element is not visible, do something else
}
});
The issue, is that once the button is in view, it triggers the click multiple time, and it loads the next 6 images multiple times back to back. I guess it's clicking multiple time since the button stays in view, not sure how to handle this.
The code for the "load more" function that works linked to that "load_more_images" button is in a "func.php" page (it's for a Wordpress site, and it's in a plugin) :
jQuery("#load_more_images").click(function() {
jQuery(this).hide();
jQuery(".load_more_wrapper .loader").show();
var ajax_url = "'.admin_url('admin-ajax.php').'";
jQuery.post(
ajax_url,
{
"action": "pd_load_more_img",
"data": {
"type": search_type,
"page":page+1,
"image_type": "'.(isset($_GET["image_type"]) ? $_GET["image_type"] : "all").'"';
if (isset($_GET['category'])){
$js.=',
"category":'.$_GET['category'];
}
if (isset($_GET['search'])){
$js.=',
"search":"'.$_GET['search'].'"';
}
$js.= '}
},
function(data){
page++;
jQuery("#images_container").append(data);
jQuery(".load_more_wrapper .loader").hide();
jQuery("#load_more_images").show();
jQuery(".category-link").dotdotdot();
}
);
});';
Any idea how I could make this work? All I need is to activate that existant function that is currently bound to a click event, but on scroll, when I reach that button, or a certain element in the page at the bottom.
Thanks a lot
You can use that function instead of your click function:-
$(window).scroll( function(e){ if($(window).scrollTop()>= jQuery('#load_more_images').position().top){ doYourFunctionHere(); } }

Remove Button is deleting all img tags and not the selected one

This is my image uploader:
My Code for adding an image which works perfect:
jQuery(function($){
// Set all variables to be used in scope
var frame, selections, attachment,
metaBox = $('#gallery-meta-box.postbox'), // Your meta box id here
addImgLink = metaBox.find('.upload-custom-img'),
delImgLink = metaBox.find('.delete-custom-img'),
imgContainer = metaBox.find('.custom-img-container'),
imgIdInput = metaBox.find('.custom-img-id' );
// Add image from frame
addImgLink.on( 'click', function( event ){
event.preventDefault();
// If the media frame already exists, reopen it
if ( frame ) {
frame.open();
return;
}
// Create a new media frame
frame = wp.media({
title: 'Select Images',
button: {
text: 'Add Image'
},
multiple: true
});
// When an image is selected in the media frame
frame.on( 'select', function() {
// Get media attachments details from the frame state
selections = frame.state().get('selection');
selections.map(function(attachment){
attachment = attachment.toJSON();
// Send the attachment URL to our custom image input field
imgContainer.append(
'<li>'
+ '<img data-attachment-id="id-media-1993'+attachment.id+'" src="'+attachment.url+'" class="gallery-thumbnail" alt="'+attachment.title+'" style="max-width:150px; max-height:150px;"/>'
+ '<a class="delete-custom-img" href="#">Remove Image</a>'
+ '</li>');
// Send the attachment id to our hidden input
imgIdInput.val(attachment.id);
console.log(attachment);
});
});
// Finally, open the modal on click
frame.open();
});
// MY DELETE BUTTON :
imgContainer.on( 'click', delImgLink, function(event){
event.preventDefault();
var galleryThumbnail = $(this).find('img');
console.log(galleryThumbnail);
});
});
When you do watch the image uploader you can see the remove links. When I click on the remove and it doesn't matter which one of the remove button it's giving my the id's of both and same for the src.
see result:
When I click on the remove link, I want information about the current image, not all the images inside my div element.
Hopefully someone can explain it.
The issue is that, while you are using event delegation to handle dynamic elements, the delegation is pre-determined, so does not pick up the elements correctly
delImgLink = metaBox.find('.delete-custom-img'),
Change
imgContainer.on( 'click', delImgLink, ...
to
imgContainer.on('click', 'a.delete-custom-img',
then this will be the button and you can find the relevant image either with .closest().find() or .prevAll("img").first() (or other method):
imgContainer.on('click', 'a.delete-custom-img', function(event){
event.preventDefault();
var galleryThumbnail = $(this).closest("li").find('img');
console.log(galleryThumbnail);
});
In your original code, if this was the delete button then
$(this).find('img')
would not find anything as find find child items and there are no child items under your delete anchor, so this must be referring to something else, higher up.
You need jquery closet() to find nearest img and then delete it.
Or you can do it by
$(this).parent().find('img');
To achieve expected reult, use below option of adding event to imageContainer images and $(this) will provide the details of selected image
$(".imgContainer img").on( 'click', function(event){
event.preventDefault();
var galleryThumbnail = $(this);
console.log(galleryThumbnail[0].id);
});
https://codepen.io/nagasai/pen/VQJoZj

How to load Photoswipe with Ajax to get server side pictures?

I'm searching for a gallery library and I see PhotoSwipe. Actually I just made the tutorial in the documentation.
I don't see any tutorial to load my server side pictures dynamically.
I need to load them with Ajax because I have a datatables, and inside each row I set an icon. The user can click on this icon and it will appears a bootstrap modal. In this modal I have to show the thumbnails related with the clicked row. And when the user click on the thumbnails I need to show the gallery.
It's possible to load dynamically server side pictures ?
I think you can achieve this by initiating the gallery from the click event. If you make this a delegated event, it will also get triggered on newly created images. Then you only need to create the image array upon triggering the click event and fire up the gallery.
Your images should be added like this:
<img class="myAjaxLoadedImage" src="myAjaxLoadedImage1_thumbnail.jpg" alt=""
data-img-title="My title 1" data-img-src="myAjaxLoadedImage1.jpg"
data-img-width="800" data-img-height="600">
<img class="myAjaxLoadedImage" src="myAjaxLoadedImage2_thumbnail.jpg" alt=""
data-img-title="My title 2" data-img-src="myAjaxLoadedImage2.jpg"
data-img-width="400" data-img-height="700">
...
And the JS would then be:
(function($) {
var pswp;
$(function() {
pswp = $('.pswp')[0];
setGalleryClickEvents();
});
function setGalleryClickEvents() {
$(document).on('click','.myAjaxLoadedImage',function(e) {
if (pswp) {
var options = {
index: $(this).index()
// + other PhotoSwipe options here...
}
var images = [];
$('.myAjaxLoadedImage').each(function() {
var $img = $(this);
images.push({
src: $img.data('imgSrc'),
w: $img.data('imgWidth'),
h: $img.data('imgHeight'),
title: $img.data('imgTitle')
});
});
var gallery = new PhotoSwipe(pswp, PhotoSwipeUI_Default, images, options);
gallery.init();
}
});
}
})(jQuery);

jQuery Lightbox gallery only working once

I am trying to build my own simple jQuery lightbox gallery. My logic behind it is as follows: Only thumbnails will be shown & created at first. These link to the full size images.
<section class="gallery-set">
<a href="img/about/gallery/a1.1.jpg">
<img src="img/about/gallery/thumb1.1.jpg" alt=""
height="192" width="383">
</a>
<a href="img/about/gallery/a1.jpg">
<img src="img/about/gallery/thumb1.jpg" alt=""
height="192" width="383">
</a>
<a href="img/about/gallery/a2.1.jpg">
<img src="img/about/gallery/thumb2.1.jpg" alt=""
height="192" width="383">
</a>
</section>
Therefore, when you click on any of these thumbnails, I dynamically create an overlay-lightbox and all full size images, showing only the one that links to the thumbnail you clicked. Although the rest of the images has been created too, these are hidden for now.
function lightBox() {
var gallery = $('.gallery-set'),
overlay = $('<div/>', {id: 'overlay'});
overlay.appendTo('body').hide();
gallery.on('click', 'a', function(event) {
event.preventDefault();
var clickedThumb = $(this),
clickedThumbPath = $(this).attr('href'),
clickedImg = $('<img>', {src: clickedThumbPath, alt: 'fullSizeImage', class: 'current'}),
prevThumbs = clickedThumb.prevAll(),
nextThumbs = clickedThumb.nextAll();
prevThumbs.each(function() {
var prevImg = $('<img>', {src: $(this).attr('href'), class: 'prev non-current'});
prevImg.appendTo(overlay);
});
clickedImg.appendTo(overlay);
nextThumbs.each(function() {
var nextImg = $('<img>', {src: $(this).attr('href'), class: 'next non-current'});
nextImg.appendTo(overlay);
});
overlay.show();
})
.....
.....
}
Now, when you click the second thumbnail, jQuery dynamically creates all the fullsize images and this is how HTML structure looks like:
Now that I have this structure, I can easily traverse the full sized images by left and right arrows. The current image gets hidden and the next one gets shown. For this logic I am using two classes, current and non-current where the first one has set display to block and the second one to none. This piece of code is within the lightbox() function:
$(document).on('keyup', function(event) {
var pressed = event.keyCode || event.which,
arrow = {left: 37, right: 39};
switch(pressed) {
case arrow.left:
var curr = overlay.find('.current'),
prev = curr.prev();
if(curr.hasClass('current')) {
curr.removeClass('current').addClass('non-current');
} else {
curr.addClass('non-current');
}
if(prev.hasClass('non-current')) {
prev.removeClass('non-current').addClass('current');
} else {
prev.addClass('current');
}
break;
case arrow.right:
var curr = overlay.find('.current'),
next = curr.next();
curr.removeClass('current').addClass('non-current');
next.removeClass('non-current').addClass('current');
break;
}
});
overlay.on('click', function() {
overlay.hide();
overlay.find('img').remove();
});
});
Everything works fine the first time. However, once I close the lightbox and try to open it again, the correct image opens but the arrows functionality is gone. I do not understand why - since I am dynamically creating the full sized images everytime user clicks on the gallery and putting event listeners (arrows) only once these have been created.
Just for the record, I am calling this lightbox() function from the HTML file right before the closing tag.
Any ideas much appreciated. Also, if there's a simpler / better way of doing this, please do let me know! I don't want to use any plugin as I think this is pretty simple and straightforward. Or, I thought it WOULD BE SIMPLE I should rather say.

trigger functions no longer working after implement ajax scroll pagination

I have developed an audio platform similar to Soundcloud and it all works(ed) perfectly! Until I decided to create an Ajax scroll pagination.
Both the pagination and Ajax work fine. However, I have noticed some JavaScript that used to work before implementing Ajax, which no longer does.
The script has a pretty simple duty; play a track when the user clicks the play button (or pause when the user clicks on it again). Then, once the track has finished, move on to the next track until it finally reaches the end.
What happens now is, when the page first loads up (along with the 10 tracks that load with the page), the script will work as it is supposed to. But, when the user scrolls down to get more results to load, if the user clicks on one of the newly loaded tracks play button, the track either won't play, or it will play over the other track which is supposed to pause (and then all the buttons just completely stop working).
Here is all of the feed.js (removed as much bloat code as possible, and placed comments):
$(document).ready(function(){ // on page load
var tp = 1; // set track page equal to one
loadTracks(tp); // then load all of the tracks
jQuery(function($) {
$('.f-outer-container').on('scroll', function() { // when the user scrolls to the bottom of the page load more tracks
if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
tp++;
loadTracks(tp);
}
});
});
function loadTracks(track_page){
$.post('/spectrum-rr/core/_func/functions/loadTrack.php', {'page': tp}, function(data){ // get send and get data from loadTrack.php
$("#f-ap__aj").append(data); // append those tracks in the feed
// player functions
$(".track-w__trigger").click(function(){ // when the play button is clicked
var tid = $(this).attr('aria-trackid'), // get its track id
tiW = 'w' + tid + 'w',
tiW = eval(tiW); // set the waveform object
playPauseButton(this, tiW, tid);
});
});
}
});
// player functionality
function playPauseButton(button, wave, trackID){ // once the function has been called
pausePrevious(button); // pause the previous track (this doesn't work when more ajax results are loaded)
var button = $(button);
if(wave.isPlaying()){ // if the wave is playing; stop it
button.removeClass("playing");
wave.pause();
} else { // vice versa
button.addClass("playing");
wave.play();
}
var waveDuration = wave.getDuration();
var nextTrack = ++trackID;
var checkAudioFinished = setInterval(function(){ // check if the audio has finished playing every second
if(wave.getCurrentTime() >= waveDuration){ // if it has
button.removeClass("playing"); // remove it's buttons "playing" class
$('#w' + nextTrack + 'w-trigger').trigger('click'); // play the next song on the playlist by incrementing the id
clearInterval(checkAudioFinished);
}
}, 1000);
}
function pausePrevious(b){
$(".playing").not(b).each(function(){ // when this function is triggered
$(".playing").trigger('click'); // pause all of the other tracks (by simulating the click of their pause buttons
$(".playing").removeClass("playing"); // remove it's class too
});
}
I feel these problems are occurring due to the use of $(document).ready();. Forcing these functions to only be available to those tracks that were already loaded. However, I am not sure.
Here is the HTML that gets sent back from each request (in 10s):
<div class="f-wave-send f-waveform-container">
<div aria-trackid="1" class="track-w__trigger" id="w1w-trigger"></div> <!-- the "1" is generated by PHP. it is incremented for every div !-->
<div class="f-waveform-outer-container">
<div aria-trackid="1" class="track-w__waveform" id="w1-w"></div>
<script>
var w1w = WaveSurfer.create({ // wavesurfer script (this is the "wave" object that is being triggered inside the playPauseButton() function !-->
container: '#w1-w',
barWidth: 2,
});
w1w.load('./player/audio/sampleaudio.mp3');
</script>
</div>
</div>
If anyone could give me insight as to what might be going on (or any tips in improving my code for that matter), it would be greatly appreciated!
Try this,
You should not bind an click event each time load happens and it should be moved out of your loadTracks, instead you shuold apply event delegation.
// player functions
$(document).on('click', '.track-w__trigger', function(){ // when the play button is clicked
var tid = $(this).attr('aria-trackid'), // get its track id
tiW = 'w' + tid + 'w',
tiW = eval(tiW); // set the waveform object
playPauseButton(this, tiW, tid);
});
Change your code to this
$(document).ready(function(){ // on page load
var tp = 1; // set track page equal to one
loadTracks(tp); // then load all of the tracks
jQuery(function($) {
$('.f-outer-container').on('scroll', function() { // when the user scrolls to the bottom of the page load more tracks
if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
tp++;
loadTracks(tp);
}
});
});
function loadTracks(track_page){
$.post('/spectrum-rr/core/_func/functions/loadTrack.php', {'page': tp}, function(data){ // get send and get data from loadTrack.php
$("#f-ap__aj").append(data); // append those tracks in the feed
});
}
// player functions
$(".track-w__trigger").on("click",function(){ // when the play button is clicked
var tid = $(this).attr('aria-trackid'); // get its track id
tiW = 'w' + tid + 'w';
tiW = eval(tiW); // set the waveform object
playPauseButton(this, tiW, tid);
});
});
Just move out $(".track-w__trigger").click outside $.post and change it to $(".track-w__trigger").on("click",function()

Categories

Resources