jQuery gallery not triggering after Ajax - javascript

I am using a jQuery pop-up script Magnific Popup. It works well in a WooCommerce store but when I filter products using an Ajax Filter Plugin (YITH) it stops triggering. I understand this is because Ajax has changed the page and so the event is no longer bound to the link class in the page but not sure how to solve it.
From what I have read I can use on but I am unsure how this applies to the way I am triggering the Magnific Popup script which is below.
jQuery('.product').magnificPopup({
type:'inline',
midClick: true,
gallery:{
enabled:false
},
delegate: 'a.wpb_wl_preview',
removalDelay: 500, //delay removal by X to allow out-animation
callbacks: {
beforeOpen: function() {
this.st.mainClass = this.st.el.attr('data-effect');
}
},
closeOnContentClick: false,
});

Thank you all. I have found there is a jQuery function to detect when Ajax has been executed which is below. Not sure if this is the best method, so interested to see other answers but this works.
jQuery(document).ajaxSuccess(function() {
//code to trigger here
});

Related

Ajax affecting jQuery document load on ajax form

I have the following jquery affecting cancelled bookings in a Drupal view, which works great.
jQuery(document).ready(function(){
jQuery(".bookingstatus:contains('Cancelled')").css("color","red");
});
But, the drupal view uses a autosubmit checkbox to load bookings based on a chosen year, in an ajax display, when a user submits a change and ajax loads the new form, the jquery isn't used again. That makes sense though, as the (document).ready will only fire once when the user enters the page, and not on every ajax request.
Updated:
This is what I am currently using, no more errors, and the colours show on the first page load like they did before, but the colours still aren't being changed after an ajax click.
(function ($) {
$.post("/", $("#views-exposed-form-bookings-block").serialize(), function() {
$(".bookingstatus:contains('Cancelled')").css("color","red");
$(".bookingstatus:contains('Full Amount Paid')").css("color","green");
$(".bookingstatus:contains('Deposit Paid')").css("color","blue");
});
})(jQuery);
.delegate and .on only help with binding events; you aren't trying to bind any events. You should instead be using the ajax-submit success or complete callbacks.
$.post("act.php", $(theform).serialize(), function() {
$(".bookingstatus:contains('Cancelled')").css("color","red");
});
Thanks to #Kevin B for your help, but the problem was with Drupal & views Ajax behaviours.
Sticking the jquery into a behaviour fixed it.
(function($) {
Drupal.behaviors.myBehavior = {
attach: function (context, settings) {
$(".bookingstatus:contains('Cancelled')").css("color","red");
$(".bookingstatus:contains('Full Amount Paid')").css("color","green");
$(".bookingstatus:contains('Deposit Paid')").css("color","blue");
}
};
})(jQuery);

Processing a PHP request from an ajax-driven Fancybox element on the same page

I've been working on a little project that involves collecting/processing search results and I thought you guys may be able to lend a hand. I have a small script that takes a search value from a search input, processes it via PHP and then collects and inserts the results in a fancybox via JS. Thus far, all is going well but I can't seem to work out the next bit.
I can't manage to interact with any elements in the fancy box because it will reload the page (for example, previous and next buttons or search input). How would you go about loading new content or form inputs into a fancybox on the same page instance using AJAX?
HTML:
<form action="search.php" method="post" name="search" id="search">
<input size="35" value="" placeholder="Search" name="search" id="result" autocomplete="off">
<button id="check" data-fancybox-type="ajax" href="search/search.php" id="check">Search</button>
Script:
jQuery(document).ready(function(submit) {
$('#check').on("click", function (e) {
e.preventDefault();
$.ajax({
type: "POST",
cache: false,
url: "search.php",
data: $("#result").serializeArray(),
success: function (data) {
// on success, post returned data in fancybox
$.fancybox(data, {
// fancybox API options
fitToView: true,
openEffect: 'fade',
closeEffect: 'fade'
});
}
});
});
});
The above script is largely basses on this post
Thanks for your ideas!
The fancybox API provides a number of event based callback functions for interacting with the fancybox elements, before, during and after the box is shown or loaded. This allows you a lot of flexibility.
I would use the afterLoad() callback function within the Fancybox2 API.
See this fiddle i put together: Fancybox afterLoad() callback to return a function
This is just my solution, I am still very much a student of js, so I can't say this is the best way, and I welcome feedback or edits.
Basically we will use the afterLoad() API function of fancybox so that upon successful load of the fancybox element driven from your successful $.ajax call a function is returned to then listen to the click event of an element loaded into your fancybox.
$.fancybox(echoData, {
// fancybox API options
fitToView: true,
openEffect: 'fade',
closeEffect: 'fade',
afterLoad: function () {
return fancyUpdateMyWay = function () {
var a = Math.random();
var newHtml = "<h4>UPDATED=" + a + "</h4>";
$("#fancyResult").html(newHtml);
}
}
});
Note: I imagine that you will want to do further ajax calls from within the fancybox results, and here I only demonstrated a simple DOM update from jquery.
try changing your javascript to use 'click' instead of 'on'. this should do it
jQuery(document).ready(function(submit) {
$('#check').click(function (e) {
e.preventDefault();
$.ajax({
....
});
});
});

How to open a magnific popup on page load?

I'm using Magnific Popup and I would like to have a video come up as soon as the page loads in a popup.
I got the plugin to work fine, but I have no idea on how to get it to pop up as soon as the page loads, without clicking on the thumbnail.
I looked around for a solution, but I did not manage to get it to work.
If you're using jQuery you could just listen for the window load event and then call the open method for your Magnific Popup like so:
(function($) {
$(window).load(function () {
// retrieved this line of code from http://dimsemenov.com/plugins/magnific-popup/documentation.html#api
$.magnificPopup.open({
items: {
src: 'someimage.jpg'
},
type: 'image'
// You may add options here, they're exactly the same as for $.fn.magnificPopup call
// Note that some settings that rely on click event (like disableOn or midClick) will not work here
}, 0);
});
})(jQuery);
I was able to get a timed modal working using jquery's setTimeout function, Just wrap .magificpopup in the settimeout function to set a delay. Change the value of 5000 (5 seconds) to whatever value you want.
See below:
$(document).ready(function () {
setTimeout(function() {
if ($('#myModal').length) {
$.magnificPopup.open({
items: {
src: '#myModal'
},
type: 'inline'
});
}
}, 5000);
});

jQuery UI DatePicker Hangs on second call

I'm creating an ASP.NET MVC3 app that uses jQuery Datepicker and Timepicker inside a dialog. The code is pretty simple, just localization:
$(document).ready(function () {
$('.datepicker').datepicker({
dateFormat: "dd/mm/yy",
monthNames: ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'],
dayNames: ['Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado'],
dayNamesMin:['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb'],
});
$('.timepicker').timepicker({
timeOnlyTitle: 'Titulo',
timeText: 'Tempo',
hourText: 'Hora',
minuteText: 'Minuto',
secondText: 'Segundo',
currentText: 'Atual',
closeText: 'Fechar'
});
});
No secret here.
The datepicker works fine when used for the first time. When I used a second time, the browser (any browser) hangs and offers me to stop script execution of jquery-1.6.4.min.js. To reproduce the error, I just reload the whole page.
What am I missing here?
Update
Adding code for the modal:
First, I configure that everything with class='modal' will have some basic parameters:
$('.modal').dialog({
resizable: false,
draggable: false,
modal: true,
position: 'center',
autoOpen: false
});
Then, I extend jQuery with some functions. One of them sets the buttons and submits:
$.extend({
modalPopup: function (modal) {
var $modal = $('#' + modal);
var $form = $modal.find('form').first();
$modal.dialog({
buttons: {
"OK": function (e) {
$.validator.unobtrusive.parse($form);
if ($form.valid()) {
$('.ui-dialog button:contains("OK")').button('disable');
$.post($form.attr('action'),
$form.serialize(),
function (data) {
$modal.dialog('close');
$('#maindiv').load(telaAtual);
});
}
},
"Cancelar": function () { $(this).dialog("close"); }
},
open: function () {
$modal.unbind('submit');
$modal.submit(function () {
$modal.parents('.ui-dialog').first().find('.ui-button').first().click();
return false;
});
$(this).find('.ui-dialog :input').first().blur();
}
})
.dialog('open');
}
})
UPDATE
I did some research and found that the problem is with DatePicker and Ajax. Everytime Maybe the Datepicker is "double called" everytime an ajax call is made. Something very similar to this question. But the Datepicker hangs even if I just close the dialog, meaning that the problem starts when the first ajax call is made.
Anyone can help me to fix this? Maybe returning false somewhere or destroying the datepicker before creating a new one.
UPDATE 01/12/2012
Sorry for the delay, guys and thanks for the help.
None of the solutions posted here worked. But, again, I thank you all for the help.
I found a boolean property $.datepicker.initialized that returns false on the first time I load the dialog, and returns true the second time. Now I can avoid the crash the second time. First problem solved.
But I still don't know how to "reinitialize" the datepicker so it can be shown when the textbox is clicked.
Still looking for a way to reinitialize it.
Also, changed the OK button code to this and works fine:
"OK": function (e) {
$.validator.unobtrusive.parse($form);
if ($form.valid()) {
$modal.parents('.ui-dialog').find('button:contains("OK")').button('disable');
$.post($form.attr('action'),
$form.serialize(),
function (data) {
if (submodal) {
carregaParcial(titulo, id);
}
else {
$('#maindiv').html(data);
}
removeModal($modal);
});
}
The $form.serialize() function already returns the html in the data variable, so, I just need to get its content and set as HTML of the maindiv.
Try this jquery datetimepicker function when submit the dialog or cancel the dialog.
$('.datepicker').datepicker("destroy");
You are using the "load" method incorrectly for your purposes. jQuery default behavior for load method when no selector is passed is to go to the URL specified, execute the JavaScript that exists on that page then load in the DOM into the jQuery object calling it.
If you pass a selector into your load method, the jQuery load method will not execute the script and will only load the dom in you jQuery object.
Change it to:
$('#maindiv').load(telaAtual + ' #maindiv > *')
This assumes your "telaAtual" URL has #maindiv on the page and then gets all of its children and loads them into "#maindiv" jQuery object.
We can go further and find out the particulars of the hanging but solving the load issue will be the first thing to consider. If it continues hanging it is worth further investigation.
Just a guess, not an answer:
Try to remove the dialog, not just close it.
...
$modal.dialog('close');
$modal.remove();
...
Maybe that helps?
BTW: With this you are clicking on the "OK" button by opening the dialog, don't you?
$modal.parents('.ui-dialog').first().find('.ui-button').first().click();
And then you load some content, so that happens when the dialog is opening?
$('#maindiv').load(telaAtual);
And if the telaAtual returns content which will open the dialog again, you are maybe stucked in an endless loop?
In this code the only very minor syntax issue might be the last unnecessary comma after the dayNamesMin. Shouldn't cause any hanging, but remove it and give it a try. Other than that this code looks fine, so the issue is somewhere else.
I've the same issue here, and in my case, that solution worked:
http://forum.jquery.com/topic/datepicker-in-modal-dialog-problem-with-populating-a-date-field
I just assign a random string to datepicker's input ID.

Jquery Fancybox not working after postback

I have a Fancybox (or more accurately) a number of fancy boxes on an asp.net page.
My Fancybox (jquery plugin) works fine until a postback occurs on the page then it refuses to work.
Any thoughts? Anyone experienced similar behaviour?
UPDATE : Some Code..
I have a databound repeater with a fancybox on each repeating item.
They are instanciated by (outside the repeater)
$(document).ready(function() {
$("a.watchvideo").fancybox({
'overlayShow': false,
'frameWidth' : 480,
'frameHeight' : 400
});
});
The anchor tag is repeated..
href="#watchvideo_<%#Eval("VideoId")%>"
As is a div with
id="watchvideo_<%#Eval("VideoId") %>
As is a script element that instanciates the flash movies
Yes the VideoIds are being output the the page.
UPDATE : It's not a problem with the flash..
It is not a problem with the flash as i've tried it without the flash, it wont even pop a window with a simple message in.
UPDATE : I wonder if it is the updatepanel.
Rebinding events in jQuery after Ajax update (updatepanel)
-- lee
The problem is in using $(document).ready() to bind the fancybox. This code is only executed once, when the page is originally loaded. If you want the fancybox functionality on every postback, synchronous or asynchronous, replace the $(document).ready() with pageLoad(sender, args). i.e.
function pageLoad(sender, args) {
$("a.watchvideo").fancybox({
'overlayShow': false,
'frameWidth' : 480,
'frameHeight' : 400
});
}
see this answer for more info
Could it be that the instantiating code is being inserted at a piece of code which is not run after a postback?
It was the Update panel as described
here.. Rebinding events in jQuery after Ajax update (updatepanel)
As suggested I simply replaced
$(document).ready(function() {
$("a.watchvideo").fancybox({
'overlayShow': false,
'frameWidth' : 480,
'frameHeight' : 400
});
});
with
function pageLoad(sender, args)
{
if(args.get_isPartialLoad())
{
$("a.watchvideo").fancybox({
'overlayShow': false,
'frameWidth' : 480,
'frameHeight' : 400
});
}
}
and it worked!
-- Lee
This might help someone else, but FancyBox appends it's code to the <body> element... which is all fine and well, but resides OUTSIDE the asp.net <form> element. My postback problems went away when I modified FancyBox to append its dom objects to the <form> element:
$('body form:first').append( ... );
I had a similar problem with a paged grid-view. The first page of the grid was launching the fancybox while the remaing did not.
I thought it could be an issue related to the UpdatePanel which refreshes only a portion of the screen.
I solved the issue replacing this:
<script>
$(document).ready(function () {
$("a.small").fancybox();
});
</script>
with this:
<script>
function pageLoad(sender, args) {
$("a.small").fancybox();
};
</script>

Categories