Is there any way to run a script again after an ajax call?
I have a photoswipe (lightbox) jquery plug-in I call like this:
jQuery(document).ready(function($){
if( $('.img-frame a').length > 0 ){
var myPhotoSwipe = $(".img-frame a").photoSwipe();
}
});
I also have an ajax 'load more posts' function, and obviously photoswipe doesn't target images loaded after the first page load.
I don't have much ajax knowledge, any help on this? Thanks
UPDATE: Here's the 'load more' script:
jQuery(document).ready(function($) {
// The number of the next page to load (/page/x/).
var pageNum = parseInt(djwd_load_posts.startPage) + 1;
// The maximum number of pages the current query can return.
var max = parseInt(djwd_load_posts.maxPages);
// The link of the next page of posts.
var nextLink = djwd_load_posts.nextLink;
/**
* Replace the traditional navigation with our own,
* but only if there is at least one page of new posts to load.
*/
if(pageNum <= max) {
// Insert the "More Posts" link.
$('#content')
.append('<div class="lp-placeholder-'+ pageNum +'"></div>')
.append('<p id="lp-load-posts" class="long-button">Load More Posts<i class="icon-chevron-down icon-large"></i></p>');
// Remove the traditional navigation.
$('#nav-below').remove();
}
/**
* Load new posts when the link is clicked.
*/
$('#lp-load-posts a').click(function() {
// Are there more posts to load?
if(pageNum <= max) {
// Show that we're working.
$(this).text('Loading posts...');
$('.lp-placeholder-'+ pageNum).load(nextLink + ' .post',
function() {
$( this ).hide().fadeIn(700);
// Update page number and nextLink.
pageNum++;
nextLink = nextLink.replace(/\/page\/[0-9]?/, '/page/'+ pageNum);
// Add a new placeholder, for when user clicks again.
$('#lp-load-posts')
.before('<div class="lp-placeholder-'+ pageNum +'"></div>')
// Update the button message.
if(pageNum <= max) {
$('#lp-load-posts a').text('Load More Posts');
} else {
$('#lp-load-posts a').text('No more posts to load.');
}
}
);
} else {
$('#lp-load-posts a').append('.');
}
return false;
});
});
I call it in Wordpress functions.php this way:
function djwd_ajax_load_init() {
global $wp_query;
if( !is_singular() ) {
wp_enqueue_script('ajax-load-posts', get_template_directory_uri() . '/js/ajax-load-posts.js', array('jquery'), true );
$max = $wp_query->max_num_pages;
$paged = ( get_query_var('paged') > 1 ) ? get_query_var('paged') : 1;
wp_localize_script(
'ajax-load-posts',
'djwd_load_posts',
array(
'startPage' => $paged,
'maxPages' => $max,
'nextLink' => next_posts($max, false)
)
);
}
}
add_action('template_redirect', 'djwd_ajax_load_init');
Put it in a function, call in on pageload and in your ajax call.
function setMyPhotoSwipe() {
var $targets = $('.img-frame a').not('.photo-swipe');
if($targets.length > 0 ){
$targets.addClass('photo-swipe').photoSwipe();
};
};
jQuery(document).ready(function($){
setMyPhotoSwipe();
});
By the way, if dont't need variable myPhotoSwipe, then you dont't have to set it. You are also using $('.img-frame a') twice, so cache the result.
And your load call:
$('.lp-placeholder-'+ pageNum).load(nextLink + ' .post',
function() {
$( this ).hide().fadeIn(700);
// Update page number and nextLink.
pageNum++;
nextLink = nextLink.replace(/\/page\/[0-9]?/, '/page/'+ pageNum);
// Add a new placeholder, for when user clicks again.
$('#lp-load-posts')
.before('<div class="lp-placeholder-'+ pageNum +'"></div>')
// Update the button message.
if(pageNum <= max) {
$('#lp-load-posts a').text('Load More Posts');
} else {
$('#lp-load-posts a').text('No more posts to load.');
}
// New content has been loaded and insertet, so set up photo swipe
setMyPhotoSwipe();
}
);
There is no delegation for plugin, its up to author's plugin to incorporate it. Why not cheating: (sorry, cannot test code and not sure its relevant to photoSwipe plugin)
jQuery(document).ready(function($){
$(this).on('mousedown','.img-frame a',function(){ //document or better parent container// mousedown or any relevent event use by photoSwipe
if(!$(this).data('swiped')) {
$(this).data('swiped',true).photoSwipe();
}
});
});
$.ajax({
url: 'url/test.php',
success: function(data) { // also gets response from php and can be manipulated if required!
setMyPhotoSwipe();
}
});
I would suggest the below
jQuery(document).ready(InitializeSettings);
also call the same in ajax calls
ajax_success_function(){ // depends on your ajax call
InitializeSettings();
}
function InitializeSettings(){
if( $('.img-frame a').length > 0 ){
var myPhotoSwipe = $(".img-frame a").photoSwipe();
}
}
Like Morpheus said.
Create a seperate function that put your code in that.
You can call that function inside your $(document).ready()
Then use that same function in your ajax success path (check documentation: http://api.jquery.com/jQuery.ajax/).
Alternatively you can use this: http://api.jquery.com/ajaxStop/
It will facilitate you to use the same function when your every Ajax Call stops.
Sorry I'm a novice in jquery... How about using ajaxComplete()
http://api.jquery.com/ajaxcomplete/
Once I had to execute a function after ajax call... and ajaxComplete() did the trick...
$(document).ready(function(){
function some_function()
{
//---- this function to be called after ajax request...
}
$( document ).ajaxComplete(function() {
some_function();
});
})
Related
I am trying to call a function after the image loads completely in DOM.
The image structure is created dynamically on AJAX call success and the image url is also added in success using the result of API call.
Problem:
I want to call a function after the image loads completely in DOM.
To do this I have used JQuery load event.
Function which is called on load.
function carouselHeight() {
$('.home-banner-img-container').each(function() {
var $this = $(this);
var dynamicheight = $(this).parent();
var sectionInnerHeight = $this.innerHeight();
dynamicheight.css({
'height': sectionInnerHeight
});
});
}
I have tried below steps but it didn't worked
$(window).on('load', function() {
carouselHeight();
});
$(window).on('load', 'img.image-preview', function() {
carouselHeight();
});
$(document).on('load', 'img.image-preview', function() {
carouselHeight();
});
The first method $(window).on('load', function() {}) works perfectly on hard reload but on normal reload it is not able to find $('.home-banner-img-container') element which is inside of carouselHeight function.
Please help me to find a solution for this. Thank you.
I have found the solution on stack overflow where I have added the below code in ajax call complete method.
function imageLoaded() {
// function to invoke for loaded image
// decrement the counter
counter--;
if( counter === 0 ) {
// counter is 0 which means the last
// one loaded, so do something else
}
}
var images = $('img');
var counter = images.length; // initialize the counter
images.each(function() {
if( this.complete ) {
imageLoaded.call( this );
} else {
$(this).one('load', imageLoaded);
}
});
I need to process an AJAX request twice, first, when the site has been opened first time, and second, when a button is clicked. I dont want to write 2 similar functions. So I created an ajaxPost function. I wonder how to detect what event has called the ajaxPost function? opening the browser or clicking a button?
function ajaxPost() {
url = "post.php";
if (this!=Window) {
button = $(this).attr("class");
} else {
button = "";
}
var posting = $.post(url,{"button": button});
posting.done(function(data) {
$(".word").html(data);
});
}
$(document).ready(function() {
ajaxPost();
$("input[type=button]").click(ajaxPost);
});
Check for the jQuery event that you're passing with a click.
function ajaxPost(event) {
url = "post.php";
if (event == undefined || event == null) { //Was not generated by a user click
button = $(this).attr("class");
} else {
button = "";
}
var posting = $.post(url,{"button": button});
posting.done(function(data) {
$(".word").html(data);
});
}
$(document).ready(function() {
ajaxPost();
$("input[type=button]").click(ajaxPost);
});
A simple solution would be to include an additional parameter when calling the function:
function ajaxPost( caller ) {
switch( caller ){
case "initial_load":
// called on page load
break;
case "button_click":
// called on button click
break;
}
...
}
Now you would need to pass this parameter from the two different types of calls:
$(document).ready(function() {
ajaxPost( "initial_load" );
$("input[type=button]").on( "click", function(){
ajaxPost( "button_click" );
});
});
So this question is not necessarily how to get it to work, because it does. But it is very very buggy. The problem I'm having is that when you scroll down, it sometimes takes a while to load so that the function reactivates or something. Either way the variable is reset and it loads like 5 pages in a row. So it's buggy. I have the code here:
var ldid = 10;
jQuery(
function ($) {
$('#allpostcontainer').bind('scroll', function () {
if ($(this).scrollTop() +
$(this).innerHeight() >= $(this)[0].scrollHeight) {
$("#allpostcontainer").append($("<div>").load("/streampage.php?id=" + ldid, function () {
ldid = ldid + 10;
}));
}
})
}
);
You can use a flag.
If it is loading you can set it to true.
If loading finished you set it back to false
and you make ajax request only if it is false.
var ldid = 10,
isPageLoading = false;
jQuery(
function ($) {
$('#allpostcontainer').bind('scroll', function () {
if ($(this).scrollTop() +
$(this).innerHeight() >= $(this)[0].scrollHeight && !isPageLoading) {
isPageLoading = true;
$("#allpostcontainer").append($("<div>").load("/streampage.php?id=" + ldid, function () {
ldid = ldid + 10;
isPageLoading = false;
}));
}
})
}
);
If you want to set your Div tag at the end of the "allpostcontainer" div then put below script in your page.
(#bottom is Div tag id which you need to display at the bottom. #allpostcontainer is div tag id which is main Div with scroll)
<script>
$(document).ready(function () {
$('#bottom').css('position', 'absolute');
$('#bottom').css('top', $('#allpostcontainer').height() - $('#bottom').height());
});
</script>
Please let me know if you have any query.
Thank you...
when I click on the log in button the pop up open correctly. But when I close it and again click on the log in button without refreshing the page, it doesn't appear.
my code is:
<script type="text/javascript">
load_login_page = function() {
$.get(HOST_NAME + "e_commerce/ECommerces/ecommerce_login", {}, function(data) {
$("#temp_login_box").html(data);
$.blockUI({
message:$('#temp_login_box'),
css:{
top:($(window).height() - 300) / 2 + 'px',
left:($(window).width() - 800) / 2 + 'px',
width:'620px',
border:'none',
background:'none',
cursor:'default'
},
overlayCSS:{ backgroundColor:'#333' }
});
load_login_ajax_form();
});
};
load_login_ajax_form = function () {
var options = {
beforeSubmit:show_login_request, // pre-submit callback
success:show_login_response // post-submit callback
};
$('#product_info_form').ajaxForm(options);
};
show_login_request = function (formData, jqForm, options) {
return true;
};
show_login_response = function (responseText, statusText, xhr, $form) {
if (responseText == 'ok') {
// $("#temp_login_box").html(responseText);
window.location.href = HOST_NAME + "e_commerce/ECommerces/user_desboard";
//load_login_ajax_form();
} else {
$("#temp_login_box").html(responseText);
load_login_ajax_form();
}
};
hide_login_info = function() {
$.unblockUI();
};
hide_login_info is form closing function. temp_login_box is id to targeted div. please help me out with this code.
Please trace your function load_login_page to check whether $.get called every time.
because you are creating $.blockUI in success of $.get
To check more i need $.unblockUI Code.
But what i suggest is, in unblockUI function either you do empty the div or hide it.
If you hide it then to show on click you have to write $().show(); in $.blockUI function
if it is not the reason
provide $.unblockUI code then might be i can help you.
Note is jquery selector for the div you hide
I am using this script from: http://pop.seaofclouds.com/
The problem is if you call the script multiple times it causes a cascading effect of a pop-out within a pop-out for as many times as you call the script.
I'm trying to figure out how to prevent it from executing when the popout has already been set. Here's the script:
//
// pop! for jQuery
// v0.2 requires jQuery v1.2 or later
//
// Licensed under the MIT:
// http://www.opensource.org/licenses/mit-license.php
//
// Copyright 2007,2008 SEAOFCLOUDS [http://seaofclouds.com]
//
(function($) {
$.pop = function(options){
// inject html wrapper
function initpops (){
$(".pop").each(function() {
var pop_classes = $(this).attr("class");
if ( $(this).find('.pop_menu').length) {
// do nothing
} else {
$(this).addClass("pop_menu");
$(this).wrap("<div class='"+pop_classes+"'></div>");
$(".pop_menu").attr("class", "pop_menu");
$(this).before(" \
<div class='pop_toggle'></div> \
");
}
});
}
initpops();
// assign reverse z-indexes to each pop
var totalpops = $(".pop").length + 100;
$(".pop").each(function(i) {
var popzindex = totalpops - i;
$(this).css({ zIndex: popzindex });
});
// close pops if user clicks outside of pop
activePop = null;
function closeInactivePop() {
$(".pop").each(function (i) {
if ($(this).hasClass('active') && i!=activePop) {
$(this).removeClass('active');
}
});
return false;
}
$(".pop").mouseover(function() { activePop = $(".pop").index(this); });
$(".pop").mouseout(function() { activePop = null; });
$("body").on("click", ".pop", function(){
closeInactivePop();
});
// toggle that pop
$("body").on("click", ".pop_toggle", function(){
$(this).parent(".pop").toggleClass("active");
});
}
})(jQuery);
now when i load this script on an ajax call the new pop-out menus work but the old ones do not react to the onclick event.
You shouldn't mess with the plugin. It works exactly like it should.
Better show us how you call this on elements that you already have.
Also I don't like this plugin. Better use something from JqueryUI
You can do such thing in much easier way.
[edit]
I tried your first code (the plugin) and it works correctly for me.
[edit]
OK. I get it. You call $.pop(); multiple times. You shouldn't! Calling $.pop(); will pin up the drop down menu to all elements that has class="pop". This is the reason why you have such funny stack.
Just use $.pop(); once.
Plugin doesn't give ability to connect NEW elements that was dynamically created on the page.
Removed pop from ajax call and just called this on success:
$(".pop").each(function() {
var pop_classes = $(this).attr("class");
if ( $(this).find('.pop_menu').length) {
// do nothing
} else {
$(this).addClass("pop_menu");
$(this).wrap("<div class='"+pop_classes+"'></div>");
$(".pop_menu").attr("class", "pop_menu");
$(this).before(" \
<div class='pop_toggle'></div> \
");
}
});
// assign reverse z-indexes to each pop
var totalpops = $(".pop").length + 100;
$(".pop").each(function(i) {
var popzindex = totalpops - i;
$(this).css({ zIndex: popzindex });
});
// close pops if user clicks outside of pop
activePop = null;
function closeInactivePop() {
$(".pop").each(function (i) {
if ($(this).hasClass('active') && i!=activePop) {
$(this).removeClass('active');
}
});
return false;
}
$(".pop").mouseover(function() { activePop = $(".pop").index(this); });
$(".pop").mouseout(function() { activePop = null; });