jquery - dynamic element height set by AJAX success - javascript

I have a collapsed list.
On Ajax success, list auto-expands.
I'm trying to get height of that expanded list ... and failing.
Ajax adds dynamically elements to list, so height changes.
Here is stripped code:
$('form').submit(function() {
$.ajax({
type: "POST",
url: "ajax/ajax.php",
data: {data:JSON.stringify(data)},
dataType: "json",
success: function(x) {
$('#slider' + x.id).children('ul,li').slideDown("slow");
//this does not return expected height (outerHeight() also tried)
var t = $('#slider_' + x.id).height();
}
});
return false;
});

I'm assuming the slideDown animation takes it time and when you've tried to get the height it has already changed.
You could use a callback for your animation, and get the height after the animation is over:
$('#slider' + x.id).children('ul,li').slideDown("slow", function()
{
//this executes AFTER the animation is complete.
var t = $('#slider_' + x.id).height();
}

Related

jquery mobile autocomplete , to show message while searching

I am using jquery mobile auto complete , Please see the demo at http://jsfiddle.net/Q8dBH/11/.
So whenever user press any letter,i need to show some message like "please wait."
So i added some code like below.But its showing only 1st time or 2nd time or not showing at all some times..How to show message whenever user types something until server responds back with data.
$ul.html('<center>Searching Please Wait<br><img src="http://freegifts.in/diet/themes/images/ajax-loader.gif"></center>');
my full js is below.
$(document).on("pagecreate", ".ui-responsive-panel", function () {
$(document).on("click", "li", function () {
var text = $(this).text();
$(this).closest("ul").prev("form").find("input").val(text); });
$("#autocomplete").on("filterablebeforefilter", function (e, data) {
var $ul = $(this),
$input = $(data.input),
value = $input.val(),
html = "";
$ul.html("");
if (value && value.length >0) {
$ul.html('<center>Searching Please Wait<br><img src="http://freegifts.in/diet/themes/images/ajax-loader.gif"></center>');
//$ul.listview("refresh");
$('.ui-responsive-panel').enhanceWithin();
$.ajax({
url: "http://freegifts.in/diet/calorie.php",
dataType: "jsonp",
crossDomain: true,
data: {
q: $input.val()
}
})
.then(function (response) {
$.each(response, function (i, val) {
html += "<li data-role='collapsible' data-iconpos='right' data-shadow='false' data-corners='false'><h2>Birds</h2>" + val + "</li>";
});
$ul.html(html);
//$ul.listview("refresh");
//$ul.trigger("updatelayout");
$('.ui-responsive-panel').enhanceWithin();
});
}
});
});
Working example: http://jsfiddle.net/Gajotres/Q8dBH/12/
Now this is a complex question. If you want to show jQuery Mobile AJAX loader there's one prerequisite, AJAX call must take longer then 50 ms (jQuery Mobile dynamic content enhancement process time will not get into account). It works in jsFiddle example but it may not work in some faster environment.
You can use this code:
$.ajax({
url: "http://freegifts.in/diet/calorie.php",
dataType: "jsonp",
crossDomain: true,
beforeSend: function() {
// This callback function will trigger before data is sent
setTimeout(function(){
$.mobile.loading('show'); // This will show ajax spinner
}, 1);
},
complete: function() {
// This callback function will trigger on data sent/received complete
setTimeout(function(){
$.mobile.loading('hide'); // This will hide ajax spinner
}, 1);
$.mobile.loading('hide'); // This will hide ajax spinner
},
data: {
q: $input.val()
}
})
beforeSend callback will trigger AJAX loader and complete callback will hide it. Of course this will work only if AJAX call lasts more then 50ms. Plus setTimeout is here because jQuery Mobile AJAX loader don't work correctly when used with web-kit browsers, it is a triggering workaround.

Using Ajax to pull image into div, how do I add height to div before call, then remove it after image is loaded?

I'm using a form and Ajax to pull an image dynamically to replace another image in the .results div. My first try worked, but the page jumped up when the image was removed and jumped back down when the image was loaded. I figured I could add style attribute to give the div a height, then after the image is loaded remove the style attribute. What I have below works 70% of the time, the other 30% the stye attribute is being removed before the image is loaded and the page jump is still there. Is there a way to remove the style attribute only after the image is completely loaded? Or set a delay or something? I'm a JS and Ajax noob, so please be gentle.
(function($){
$(function(){
var $form = $('#customize'), // Search form
$target = $('.results'), // Results container
rp = 'product_search/results_only_ajax'; // Template for results only
// Function to execute on success
var success = function(data, status, xhr) {
$target.html(data);
$('.loading').html('<p></p>');
// Remove style
$('.results').removeAttr("style");
};
// Hijack the form on submit
$form.submit(function(){
// Tell target we're loading
$('.loading').html('<p>Loading...</p>');
// get height of container, and set height
currentHeight = $('.results').outerHeight();
$('.results').css("height", currentHeight);
// Add custom result page to data
var data = $form.serialize()
+ '&result_page=' + rp;
// Perform the ajax call
$.ajax({
type: 'POST',
url: $form.attr('action'),
data: data,
success: success,
dataType: 'html'
});
// Don't submit the form afterwards
return false;
});
});
})(jQuery);
EDIT:
// Function to execute on success
var success = function(data, status, xhr) {
$target.html(data);
$('.loading').html('<p></p>');
// $('.results').removeAttr("style");
setTimeout(function () {
$('.results').removeAttr("style");
}, 1000);
};
I added a Timeout which is working ok for now.

Loading Spinner Image too fast at start of Function

I have a function that displays contents of a posts when clicked on. I want the loading spinner to display and delay for few sections before the post content appears. The issue here is when I click on each post, the spinner appears for maybe 1ms and in some cases it disappears long before the content appears.
function showPost(id) {
setTimeout(function() {$('#loader').show();},1);
$('#pcontent').empty();
$.getJSON('http://howtodeployit.com/category/daily-devotion/?json=get_post&post_id=' + id + '&callback=?', function(data) {
var $postcon = $('<div/>').append([$("<h3>", {html: data.post.title}),$("<p>", {html: data.post.content})]);
$postcon.appendTo('#pcontent');
});
}
Spinner HTML:
<div id='loader'><img src="css/images/loader.gif"/></div>
Try this:
function showPost(id) {
$('#loader').show();
$('#pcontent').empty();
$.ajax({
url: 'http://howtodeployit.com/category/daily-devotion/?json=get_post&post_id=' + id + '&callback=?',
dataType: 'json',
success: function (data) {
var $postcon = $('<div/>').append([$("<h3>", {
html: data.post.title
}), $("<p>", {
html: data.post.content
})]);
$postcon.appendTo('#pcontent');
$('#loader').hide();
}
});
}
gif image always behave differently on every device..basically it depends upon device's processing speed. so better option is to use image sprites and animate it with javascript..
In your case at page load there is nothing processing..but as page starts to load device's processor cant handle the load and as a result your gif image gets slower
It seems from your last commented line that you are using a timeout to hide the loader. Instead You should handle the hiding inside the callback function of your ajax request, so that loader hides after request is completed, not after a fixed amount of time:
function showPost(id) {
$('#loader').show();
$('#pcontent').empty();
$.getJSON('http://howtodeployit.com/category/daily-devotion/?json=get_post&post_id=' + id + '&callback=?', function(data) {
$('#loader').hide();
var $postcon = $('<div/>').append([$("<h3>", {html: data.post.title}),$("<p>", {html: data.post.content})]);
$postcon.appendTo('#pcontent');
});
}

Jquery Random Slider doesn't show all images in json array

I'm writing my first jquery code and I've to write a random slider that will get images through a php function and will show them in a sequence with some decoration. Random thing is done in php. My jquery is as follows.
function bannerSlide(){
$.ajax({
type: "GET",
url: "test.php",
dataType: 'json',
success: function(images) {
$.each(images, function (index, value) {
$('#banner').slideUp(500).delay(2000).fadeIn(500).css('background', 'url(ItemPictures/'+value+')');
});
}
});
}
I get images in images array and loop through it.
The problem I'm facing is that my this code only shows the last image in array. other images are not shown and it keeps sliding the last image of array.
But if I put an alert statement inside $.each function then image changes after I click on ok of alert box and it goes on.
Any help will be highly appreciated.
Please don't suggest to use some already built slider.
The each loop will run in microseconds and set the css value immediately on each pass with your code. Thus you only see the last image
Here's a solution using setTimeout and changing the css within the callback of the first animation so the css only gets changed at appropriate time. You may need to adjust the timeout interval index*3000
$.each(images, function(index, value) {
setTimeout(function() {
$('#banner').slideUp(500, function() {
/* use callback of animation to change element properties */
$(this).delay(2000).fadeIn(500).css('background', 'url(ItemPictures/'+value+')');
})
}, index * 3000);
});
DEMO using text change of element http://jsfiddle.net/RrPu6/
Following code is solution to the posted problem.
function bannerSlide(){
$.ajax({
type: "GET",
url: "test.php",
dataType: 'json',
success: function(imgs) {
var cnt = imgs.length;
$(function() {
setInterval(Slider, 3000);
});
function Slider() {
$('#imageSlide').fadeOut("slow", function() {
$(this).attr('src', 'ItemPictures/'+imgs[(imgs.length++) % cnt]).fadeIn("slow");
});
}
}
});
}
where imageSlide is id of an img tag inside 'banner' 'div'
The problem is that you are iterating over the array of images, and for each one you're setting the background of the same DOM element... $('#banner'). This is going to happen so fast that you'll only see the last image, at the end of the iteration. This is also why you can see it changing if you alert() in between, because execution is paused during alert().
You'll have to figure out a way to delay the changing of the background. One thing you can try is adding an increasing delay() before your slideUp(). Something like:
function bannerSlide(){
$.ajax({
type: "GET",
url: "test.php",
dataType: 'json',
success: function(images) {
var duration = 2000;
var element = $('#banner');
$.each(images, function (index, value) {
element.delay(index * duration).slideUp(500).delay(duration).fadeIn(500).css('background', 'url(ItemPictures/'+value+')');
initialDelay += duration;
});
}
});
}
It's an ugly hack, but that's why those already built sliders exist :)

What's a good way to display a loading image until an ajax query completes?

Right now it contacts the server every time a user toggles "Comments (X)"
I'd like to make it so as soon as a user clicks ".info .reply" (Comments (X)), an ajax loader appears just until the data is finished loading, then the loader disappears.
// Replies - Toggle display of comments
$('.info .reply').click( function() {
$('.reply', this.parentNode.parentNode).toggle();
return false;
});
// Load comments
$('.info .reply', this).mousedown( function() {
var id = $('form #id', this.parentNode.parentNode).val();
$.ajax({ url: location.href, type: 'post', data: 'id=' + id, dataType: 'json',
success: function(data) {
for (var i in data) {
// Do AJAX Updates
}
}
});
return false;
});
What's the proper way to do this?
Thanks!
Basically
Show the image on mousedown using show() or fadeIn() or whatever tickles your fancy, then hide it inside your success callback. Like this
$('.info .reply', this).mousedown( function() {
$("#loading-image").show(); // Show the progress indicator
var id = $('form #id', this.parentNode.parentNode).val();
$.ajax({ url: location.href, type: 'post', data: 'id=' + id, dataType: 'json',
success: function(data) {
$("#loading-image").hide(); // Hide the progress indicator
for (var i in data) {
// Do AJAX Updates
}
}
});
return false;
});
You can use a plugin such as jQuery BlockUI to do this. Just call $.blockUI() before calling $.ajax. Then at the end of the success event, call $.unblockUI().

Categories

Resources