Show loading animation when collapsible block is opening Jquery Mobile - javascript

I have a problem trying to show loading icon when collapsible block is opening. I have a collapsible block with a listview inside which is populated dynamically via ajax/php. They list might have up to 500 elements, so I would like to show loading animation while it is loading.
I have tried
$('div.century').live('expand', function(){
var idval = $(this).attr('id');
console.log('expanded'+idval);
$.mobile.showPageLoadingMsg ();
$.get("helpers/getByCentury.php", { id: idval},
function(data){
$("#"+idval+" ul.ulist").html(data);
$("#"+idval+" ul.ulist").listview('refresh');
});
$.mobile.hidePageLoadingMsg ();
});
I have also tried
$('div.century').live('expand', function(){
var idval = $(this).attr('id');
console.log('expanded'+idval);
$.mobile.pageLoading();
$.get("helpers/getByCentury.php", { id: idval},
function(data){
$("#"+idval+" ul.ulist").html(data);
$("#"+idval+" ul.ulist").listview('refresh');
});
$.mobile.pageLoading(true);
});
without any luck.
Can anyone tell me how to fix this?
Thanks in advance.

You want to call $.mobile.hidePageLoadingMsg() in the callback function for your ajax call:
$('div.century').live('expand', function(){
var idval = $(this).attr('id');
console.log('expanded'+idval);
$.mobile.showPageLoadingMsg ();
$.get("helpers/getByCentury.php", { id: idval},
function(data){
$("#"+idval+" ul.ulist").html(data);
$("#"+idval+" ul.ulist").listview('refresh');
$.mobile.hidePageLoadingMsg ();//NOTICE: this has been moved inside the callback function for your $.get() call
});
});
Also a couple pointers.
You are using the $("#"+idval+" ul.ulist") selector twice in a row, you can make that more efficient by chaining function calls together like so:
$("#"+idval+" ul.ulist").html(data).listview('refresh');
If other people view your webpage in a browser that does not have the console.log function they will get an error and your JS will stop running, it is normally a good idea to put calls to the console.log function inside a conditional that checks for the existance of that function:
if (typeof(console.log) == 'function') {
console.log('expanded'+idval);
}

Related

How do I use the .done() callback to run a function for new data being loaded on request?

I have a page displaying data from a json feed and I also have a button which loads more of the feed on click of a button. My aim is to append some content inside the page for each feed item. I have been able to create a function which does this on load of the page, but I am unsure how to make this work with the aysynchronous loading of more data.
I understand I need to use the .done() callback to make this work but need some guidance how to implement it correctly.
This function appends the new content initially:
function appendFeed() {
$('.feed__item').each(function (index) {
$feedItem = $('.feed__item', $(this));
$feedItem.append('<div class="feed-gallery"></div>');
for (var i = 1; i <= 5; i++) {
var $count = i;
if ($count > 1) {
$('.feed.gallery', $(this)).append('<div><img data-lazy="//placehold.it/50x50"></div>');
};
});
}
This is where the .done() callback is referred, on click of a button:
$('button').click(function(){
$.getJSON(uri, function (json, textStatus) {
// do stuff
}).done(function (json) {
// do stuff - in my case this would be appendFeed()
});
});
I have already called the appendFeed() function, but if I put it inside the .done() callback on click the button, then it appends the feed again. How do i prevent the duplication for the feed that is already on the page?
This is how you will write.
<script type="text/javascript">
$.getJSON("/waqar/file.php").done(function (data) {
$(".output").append(data);
});
</script>

Handling State changes jQuery and History.js

Ok, so I need some insight into working with History.js and jQuery.
I have it set up and working (just not quite as you'd expect).
What I have is as follows:
$(function() {
var History = window.History;
if ( !History.enabled ) {
return false;
}
// Capture all the links to push their url to the history stack and trigger the StateChange Event
$('.ajax-link').click(function(e) {
e.preventDefault();
var url = this.href; //Tells us which page to load
var id = $(this).data('passid'); //Pass ID -- the ID in which to save in our state object
e.preventDefault();
console.log('url: '+url+' id:'+id);
History.pushState({ 'passid' : id }, $(this).text(), url);
});
History.Adapter.bind(window, 'statechange', function() {
console.log('state changed');
var State = History.getState(),
id = State.data.editid; //the ID passed, if available
$.get(State.url,
{ id: State.data.passid },
function(response) {
$('#subContent').fadeOut(200, function(){
var newContent = $(response).find('#subContent').html();
$('#subContent').html(newContent);
var scripts = $('script');
scripts.each(function(i) {
jQuery.globalEval($(this).text());
});
$('#subContent').fadeIn(200);
});
});
});
}); //end dom ready
It works as you'd expect as far as changing the url, passing the ID, changing the content. My question is this:
If I press back/forward on my browser a couple times the subContent section will basically fadeIn/fadeOut multiple times.
Any insight is appreciated. Thanks
===================================================
Edit: The problem was in my calling all of my <script> and Eval them on each statechange. By adding a class="no-reload" to the history controlling script tag I was able to do:
var scripts = $('script').not('.no-reload');
This got rid of the problem and it now works as intended. Figure I will leave this here in case anyone else runs into the same issue as I did.
The problem was in my calling of all of my <script> and Eval them on each statechange. By adding a class="no-reload" to the history controlling script tag I was able to do:
var scripts = $('script').not('.no-reload');
This got rid of the problem and it now works as intended. Figure I will leave this here in case anyone else runs into the same issue as I did.

jquery loading when load

i have script like this
function manualSeat(){
$('.dimmed').show();
$("#petaKursi").load('url');
$('#wagonCode').val('');
$('#wagonNumber').val('');
$('#selSeats').val('');
selectedGerbong = '';
selectedSeats = Array();
$('#manualSeatMap').show();
$('.dimmed').hide();
}
that code above doesn't work maybe because code doesn't wait until load syntax finish loading,..(maybe)
what i want to ask is,how to make my $('.dimmed')
works like loading that start when begin(show) loading and stop when loading finish(hide)
what i want is like this::
page load(with every div)=>click a button=>load a page to div(when loading,showLoader),when finish loading (hideLoader)
try this:
var dimmed = $('.dimmed');
var showLoader = function () {
dimmed.fadeIn();
};
var hideLoader = function () {
dimmed.fadeOut();
};
document.addEventListener('DOMContentLoaded', showLoader);
window.onload = hideLoader;
You can call showLoader and hideLoader methods whenever you want to show or hide the loader element.
thanks to Rayon Dabre
what i actually want is like this
function manualSeat(){
dimmed.fadeIn();
$("#petaKursi").load('blablabla', function() {
dimmed.fadeOut();
});
$('#wagonCode').val('');
$('#wagonNumber').val('');
$('#selSeats').val('');
selectedGerbong = '';
selectedSeats = Array();
$('#manualSeatMap').fadeIn();
}
The best way to do what you want is to use AjaxStart and AjaxStop function. This way you will fire when the Ajax call (.load is one of them) it will perform some actions.
So in your case:
$(document).ajaxStart(function (){
//I begin the ajax call so I show the layer
$('.dimmed').show();
//you can also do other stuffs like changing the tab title
document.title = 'loading...';
}).ajaxStop(function (){
//The ajax loading has ended
$('.dimmed').hide();
document.title = 'page';
});
I'd go for an ID for the layer that you use while loading to identify it.
If you want to fire this event only for some ajax call and not for other add the
global: false
attribute to that specific ajax call.

jquery unable to show and hide an element

I have div element as
<div class="preview-image hide"><img src="{{STATIC_URL}}ui-anim_basic_16x16.gif"></div>
The hide class belongs to Twitter Bootstrap 2.3.2, the preview-image basically adds some styling to the element and used as handle for JavaScript.
I have jQuery code as below where
$loading.show() and $loading.hide() are not working.
The surprising this is when I run $preview.parent().find('.preview-image').show() from console, its working!!
(function($) {
$(document).ready(function() {
var SET_TIME = 6000;
$('[data-preview]').click(function() {
var $this = $(this);
var $preview = $('#' + $this.data('presponse'));
var $loading = $preview.parent().find('.preview-image');
$loading.show();
$.ajax({
});
$loading.hide();
});
});
})(window.jQuery);
Because $.ajax() is an asynchronous call, the $loading.hide() is being called (as it appears to the user) immediately after the $loading.show(). In order to circumvent this, you should make the $loading.hide() call after your AJAX call is complete. One way to do this is:
var $loading = $preview.parent().find('.preview-image');
$loading.show();
$.ajax({
}).always(function() {
$loading.hide();
});
Is the issue that it's hiding straight away? I think the hide needs to be within a success function of the AJAX call rather than being after it.
Eg.
$.ajax({
success: function() {
$loading.hide();
}
});

Loading GIF while AJAX completes

This should be quite simple but I'll be darned if I can work it out. Just trying to get a div to display while my ajax is processing and then hide once done (I've put a sleep in there purely to test its working as locally it loads so fast I'm not sure if its working or not)!
The html page has this code in the script: -
$(document).ready(function(){
$("#loadingGIF").ajaxStart(function () {
$(this).show();
});
$("#loadingGIF").ajaxStop(function () {
window.setTimeout(partB,5000)
$(this).hide();
});
function partB(){
//just because
}
var scenarioID = ${testScenarioInstance.id}
var myData = ${results as JSON}
populateFormData(myData, scenarioID);
});
There is then a div in my page like so (which I can see in the source of the page just hidden): -
<div id="loadingGIF" ><img src='${application.contextPath}/images/spinner.gif' height="50" width="50"></div>
The ready code then goes off and calls this: -
function populateFormData(results, scenarioID) {
$table = $('#formList')
for(var i in results){
var formIDX = (results[i]["forms_idx"])
var formID = (results[i]["form_id"])
appendSubTable(formIDX, scenarioID, $table, formID);
}
}
Which references this multiple times calling several AJAX posts: -
function appendSubTable(formIDX, scenarioID, $table, formID) {
var $subTable = $table.find("#" + formIDX).find('td:eq(1)').find("div").find("table")
var url = "**Trust me this bits OK ;) **"
$.post(url, {
formIDX : formIDX, scenarioID : scenarioID, formID :formID
}, function(data) {
$subTable.append(data)
}).fail(function() {
});
}
Any pointers gratefully received...
Interestingly I bunged some alerts into my ajaxstart and stop and neither show up ever so I'm missing something obvious :S When I check the console in firefox I can see that all my POSTs are completing....
You should probably add the Ajaxstart and stop global event handlers to the document node like this
$(document).ajaxStart(function () {
$("#loadingGIF").show();
});
I realized my problem, I needed to register the ajaxstart and stop to the document not the div!
So instead of this: -
$("#loadingGIF").ajaxStart(function () {
$(this).show();
});
I now have: -
$(document).ajaxStart(function () {
$("#loadingGIF").show();
});
I assume this is because its the document that the ajax is running against not the div although my understanding there may not be 100% accurate at least this works so please tell me if I've misunderstood this! :)
#jbl, thanks for this pointer I did this to also leave the notification on screen for a few more moments just to make sure everything is loaded.

Categories

Resources