How to determine if an html div element is completed loaded - javascript

On clicking a load button in a jsp (1.jsp), another jsp(2.jsp) is loaded in a div element of the original jsp(1.jsp).
This loaded div jsp has some large datatable and html elements that take time to configure (a few seconds.) During this time it would be useful to show the user a loading dialog or wait screen as the jsp is not fully ready.
I tried using jquery modal as well as jquery show/hide as follows
$("#loadpage").show();
$("#divElement").load("2.jsp");
$("#loadpage").hide();
but the probelm is that the hide() is called before the 2.jsp is fully loaded.
How to keep a loading gif untill the 2.jsp is fully loaded????

Just use the call back function of the load function
$("#divElement").load("2.jsp", function () {
$("#loadpage").hide();
});
Callback Function
If a "complete" callback is provided, it is executed after post-processing and HTML insertion has been performed. The callback is fired once for each element in the jQuery collection, and this is set to each DOM element in turn.
For more information you can see the JQuery Documentation of load
EDIT (after comment):
If you want to check the error you can implement the function the following way :
function(response, status, xhr) {
if (status == "error") {
// Do something on error
} else {
$("#loadpage").hide();
}
}

you can pass a function in load. it will be get called once download of 2.jsp complete.
$("#divElement").load("2.jsp", function(){
// content is loaded
});

Related

Cloning Objects in Google Optimize

I'm trying to clone a button in Google Optimize (or any other javascript/jQuery method) that adds an item into a shopping cart. My problem is that when I run the code or experiment in Optimize, the button doesn't trigger.
Here's my two different attempts. Method 1 via Optimizes' interface.
Select the button to copy, use the 'edit code' to get the html.
Use Insert HTML a the location of the new button, and insert the code.
Version 2 uses jQuery's clone();
$('#SOME-ID > PATH TO THE ELEMENT TO CLONE').clone().attr('id', 'ADD-ID-FOR-GTM-TRACKING').appendTo('#proPriceMobile');
What could the problem be?
Thanks in advance!
It's quite possible, that your experiment fires BEFORE your buttons loads on your page, in your actual browser.
Do you get an error message in console?
My tip would be to wait for your button to load, before applying the DOM changes. If possible, do this all via JavaScript.
For example, here you can wait for an element to load, via using a callback and setTimeout():
// FUNCTION WHICH WAITS FOR YOUR INITAL BUTTON to LOAD
function waitForElement(className, callBack){
window.setTimeout(function(){
// GRAB YOUR ELEMENT
var element = document.querySelectorAll(className)[0];
if(element) {
callBack(className, element);
console.log("Callback successfully fired and code executed...")
} else {
waitForElement(className, callBack);
console.log("This runs every second until your element is loaded on the page..")
}
},1000)
};
// EXECUTE THE CODE IN THIS FUNCTION, WHEN YOUR BUTTON LOADS IN THE DOM
waitForElement(".your-element-classname",function(){
console.log("Button has loaded in DOM...");
// NOW CLONE YOUR BUTTON
});
When I've cloned buttons in the past, I've lost all functionality on the cloned button. So you may need to rebuild that functionality on the cloned button.

Getting a jQuery function to fire

I have a very simple jQuery function
$('#bnAddDegree').click(function () {
alert("bnAddDegree Loaded");
});
I have broken my site into different pieces based upon what the user clicks. If they click on a tab in the menu to load a section I call a partial_html page and load the section into the center div. If I put the code above into the main page load it will not fire. If I add an external js file and load it when the page loads it will not fire, I think because the elements are not initialized yet. If I put it into an external js page that is loaded after the partial_html is loaded it will not fire. If I put it ON the partial_html page with a tag it DOES fire. If I put a simple javascript function
function testFile() {
alert("File Loaded");
}
In the places that the jQuery code will not fire it works fine.
Is there something special that I'm missing with jQuery?
When I load the javascrip file I use
$.getScript("js/biosketch.js")
And test it with the simple javascript file and it works fine but not the jQuery call.
You need to use delegated event handlers since you are modifying the DOM dynamically.
$(document).on('click', '#bnAddDegree', function () {
alert("bnAddDegree Loaded");
});

$(document).ready not working in ajax page

I'm loading my page contents dynamically with ajax and I want to load certain .js files with a function. The .js file loads fine, but only before the next page has been loaded via ajax.
For example: from homepage to biography page:
1st loads the .js file
2nd: loads the biography page (via ajax)
It looks like that the ajax page is always on state document ready. So it wil trigger immediately the .js file, before it loads the content of the biography page via ajax.
$(document).ready(function() {
$(".element").click(function() {
jQuery.getScript("http://example.com/js/file.js");
});
});
I've manage to solve this problem temporary with a timeout, so that the .js file will load after 5 seconds, so after the page biography has been loaded.
$(".element").click(function() {
setTimeout(function() {
jQuery.getScript("http://example.com/js/file.js");
}, 5000);
});
How can I change the function so that it will load the .js file as soon as the biography page has been loaded (or any other page), instead of a timeout.
EDIT1:
I've added the ajax call here:
http://jsbin.com/ediFUca
AJAX allows you to specify a callback: a function to call when the request is finished.
Put your scripts/functions in the callback and it will execute when your seconds page has completed loading, effectively solving your problem:
$.ajax({
url: "test.html"
}).done(function() {
//do things in here that should be done after the AJAX call e.g:
jQuery.getScript("http://example.com/js/file.js");
});
As you mentioned in first line that you are loading contend dynamically so your predefined click handler will not fired for content that are added later.
So you need to use event delegation.
use jQuery.on(); for that.
Sample
jQuery(document).on('click',".element",function()
{
jQuery.getScript("http://example.com/js/file.js");
});

jQuery Mobile Ajax Navigation timeout

In jQuery Mobile, if user clicks on a button, a loading icon appears and then it loads the new webpage via Ajax.
But, The server may be not respond in my case. Isn't there any way to put a timeout (e.g. 10 seconds) for ajax navigation feature? (If time limit exceeds, stop trying to navigate and show an error message)
To set a timeout i think you should not do it in a static way ( using "data-transition" )
you can make a listener to the link ('onclick') and within the listener make an ajax call to load your page. Use $.mobile.changePage() to do that.
The $.mobile.changePage() function is used in a number of places in jQuery Mobile. For example, when a link is clicked, its href attribute is normalized and then $.mobile.changePage() handles the rest.
so your code could seem like this :
$('#link_id').click(function() {
$.ajax({
url: "page_served_from_server",
error: function(jqXHR, strError){
if(strError == 'timeout')
{
//do something. Try again perhaps?
}
},
success: function(){
//charge your page :
// $.mobile.changePage('yourPageAdress',"turn",false,true);
},
// here you can specify your timeout in milliseconds
timeout:3000
});
});

jQuery Mobile load second page from new html

Say I wanna load a new html file, with some jQuery pages, like this:
$.mobile.changePage("some_page.html");
If this html file has two pages inside, how do I load not the first, but the second page?
I Tried
$.mobile.changePage("some_page.html#second_page_id");
But it doesn't work.
Thanks
Dude try to make your second page element data-url as <div data-url="page.html&subpageidentifier">
in the target html page. and let me know is that really worked for you.
The $.mobile.changePage() function takes the first div with data-role="page" and loads it into the dom with an AJAX call. The best solution is to move the second page to the top of the html code.
Otherwise, if you want to decide to load the first or second page, you could put them in different files.
Maybe there's a way of calling the second page, but i have no idea of how to accomplish this.
You can manually grab the element you want:
//delegate the event binding for some link(s)
$(document).delegate('a.my-link', 'click', function () {
//show the loading spinner
$.mobile.showPageLoadingMsg();
//make the AJAX request for the link's href attribute
$.ajax({
url : this.href,
success : function (serverResponse) {
//get the data-role="page" elements out of the server response
var $elements = $(serverResponse).find('[data-role="page"]');
//you can now access each `data-role="page` element in the `$elements` object
$elements.filter('#page-id').appendTo('body');
//now use changePage to navigate to the newly added page
$.mobile.changePage($('#page-id'), { /*options*/ });
//hide the loading spinner
$.mobile.hidePageLoadingMsg();
},
error : function (jqXHR, textStatus, errorThrown) { /*Don't forget to handler errors*/ }
});
//stop the default behavior of the link, also stop the event from bubbling
return false;
});
But I have to say, with the way jQuery Mobile currently works, you're better off putting each data-role="page" elements in a separate document.
ทำแบบนี้ครับ
ออก
สำคัญคือให้ใส่ data-ajax="false"
คุณก็จะ changepage ได้จากต่างหน้า

Categories