Reputation: 15
I now this question have been asked, but i am totally ignorance in the subject, and i can't really use the answers. I made every script of my page with tutorials, but i failed. My problem: I have a section where I load content from external html with ajax (used this tut: https://www.youtube.com/watch?v=dmfZp4iFzOs), and I have to run a js after every time I loaded a content. But the script doesn't work, because it is running before I load the content.
The html (for example):
<body>
<ul>
<li><a class="menu" href="1.html">1</a></li>
<li><a class="menu" href="2.html">2</a></li>
<li><a class="menu" href="3.html">3</a></li>
</ul>
<div id="content_area"></div>
<script src="menu.js"></script>
</body>
The menu.js:
$('.menu').click(function(){
var href = $(this).attr('href');
$('#content_area').hide().load(href).fadeIn('normal');
return false;
});
The external html is complicate but i have to run this script every time, when clicked (and loaded) a menu:
var init = function() {
var box1 = document.querySelector('.container1').children[0],
showPanelButtons = document.querySelectorAll('#show-buttons button'),
panelClassName = 'show-front',
onButtonClick = function( event ){
box1.removeClassName( panelClassName );
panelClassName = event.target.className;
box1.addClassName( panelClassName );
};
for (var i=0, len = showPanelButtons.length; i < len; i++) {
showPanelButtons[i].addEventListener( 'click', onButtonClick, false);
}
document.getElementById('toggle-backface-visibility').addEventListener( 'click', function(){
box1.toggleClassName('panels-backface-invisible');
}, false);
};
window.addEventListener( 'DOMContentLoaded', init, false);
Sorry for my bad english. Please help me! Thanks
Upvotes: 0
Views: 137
Reputation: 21
Instead of using "window.addEventListener( 'DOMContentLoaded', init, false); ", you can use a callback with jquery load()'s function.
$('#content_area').hide().load(href, init).fadeIn('normal');
Upvotes: 0
Reputation: 218798
jQuery's .load()
function is an asynchronous operation, so it's going to "return" before it completes. Thus, instead of waiting for it to return, you supply it with a "callback" function which it will invoke when it completes. Something like this:
$('#content_area').hide().load(href, function () {
init();
$('#content_area').fadeIn('normal');
});
Note a couple of things here:
.fadeIn()
call to within the callback as well, since you don't want to fade in the element until after its content is loaded.function () {}
. This function is itself a value which is passed to the .load()
function and will be invoked when .load()
has completed its work.Upvotes: 1