Reputation: 904
On my page, there are two Divs
A & B.
Div B
is hidden by default.
Div A
contains only a button
. Upon its click I want A to hide & B to be displayed.
But the contents of div B contains some data which is getting flooded by async REST calls.
So I want B to be only displayed when all of its contents are ready.
HTML:
<div id="A">
<button id="button1">Click here</button>
</div>
<div id="B"></div>
JS Code
//Approach 1 I tried:
$(document).ready(function() {
$("#B").hide(); // Div B hidden by default
$("#button1").click(function () {
$.when (
renderChildPage()
).done (
$("#B").show()
)
});
});
function renderChildPage() {
// 1. some async calls
// 2. fill some elements in Div B.
}
But above code is not working as some elements in Div B gets displayed, while some are not.
//Approach 2 I tried:
$(document).ready(function() {
$("#B").hide(); // Div B hidden by default
$("#button1").click(function (){
$("#B").show();
renderChildPage; // Code even working without it.
});
});
var renderChildPage = (function () {
// 1. some async calls
// 2. fill some elements in Div B.
})();
This approach works but even if I do not call renderChildPage()
, that function is still getting called and displaying the contents in div B.
Can some please suggest what should be the correct approach?
Also in approach 2 why the code is getting executed, without call.
Thank You
Upvotes: 1
Views: 770
Reputation: 1521
Your approach is correct. done
takes a callback and executes when when
is completed.
$(document).ready(function() {
$("#B").hide(); // Div B hidden by default
$("#button1").click(function () {
$.when (
renderChildPage();
).done (function(){
$("#B").show()
}
)
});
});
Upvotes: 1
Reputation: 3834
Do this:
).done(function() {
$("#B").show();
});
Instead of this:
).done (
$("#B").show()
)
Or just add $("#B").show();
inside renderChildPage()
function after you fill the content.
Upvotes: 1