Reputation: 1651
Summary...
I have a page that is loading other pages with ajax and they contain javascript. The javascript makes use of document.ready
which doesn't work right when using code like this...
$.ajax({
type: 'get',
url: 'layouts/' + layout + '.php',
success: function(data){
$('.swap').fadeOut('slow', function(){ // container
$(this).delay(100).fadeIn().html(data);
});
}
});
It doesn't work right in the sense that the javascript is running too fast.
What's the best way to load pages that make use of document.ready
or code like it?
Upvotes: 0
Views: 150
Reputation: 1814
When you use ajax to load a page, the javascript in that page will typically not be executed. You can use jQuerys load()
method to load the page in and then execute the scripts.
In your template page, add a <div>
to hold the actual contents of the page like so:
<div id="container">
<ul>
<li></li>
</ul>
</div>
In your "control panel" page, have a container <div>
as well:
<div id="container"></div>
<script src="bxslider.js"></script>
You could then call your code in this manner
$(function(){
var layout = 'layoutpage1';
// this loads the contents of the #container div in layout page
// into #container div on CP page.
$('#container').load( '/layouts/' + layout + '.php #container', function() {
initSlider(); // initialize the slider we just loaded
});
function initSlider() {
$('.bxslider').bxSlider({
pager: false,
controls: false,
auto: true,
mode: 'fade',
speed: 1500
});
}
// if there is already a slider on the page we can initialize it here
// just remove comment
// initSlider();
});
Upvotes: 2
Reputation: 452
I'm spotting something dead simple here, otherwise i'm being dead simple....
" $('.swap').fadeOut('slow', function(){"
You have no class labelled swap in the HTML?
Upvotes: 0
Reputation: 171669
If you use load()
method the scripts will execute. Note however that document.ready has already occurred in main page so scripts need to be after the html they reference.
Alternatively you can use $.getScript()
in success callback
$('.swap').fadeOut(function(){
$(this).load('layouts/' + layout + '.php', function(){
$(this).fadeIn()
});
})
Upvotes: 0
Reputation: 755
You can add all your scripts in your main html file before body and try to initiate their functionality in the pages your are calling with ajax.
<div>
<ul class="slider">
<li><img /></li>
<li><img /></li>
</ul>
<script>
$(document).ready(function(){
//slider.init(); start slider
})
</script>
Upvotes: 1