Reputation: 13
I have two pages which are using touchSlider(jquery library). Both are working in separate pages. But when I want to load them dynamically to index.html, the library can't work. Here is my html code and js code. Thank you so much!
index.js
$("#div1").on("click", function() {
$.getScript( "js/jquery.touchSlider.min.js", function() {
$("#main-content").html("");
$("#main-content").load("page2.html");
$('#gallery2').touchSlider({
animation: 'js',
mode: 'shift',
offset: 'auto'
});
});
$("#div2").on("click", function() {
$.getScript( "js/jquery.touchSlider.min.js", function() {
$("#main-content").html("");
$("#main-content").load("page1.html");
$('#gallery1').touchSlider({
animation: 'js',
mode: 'shift',
offset: 'auto'
});
});
index.html
<div>
<div id="div1"></div>
<div id="div2"></div>
<div class="main-content">
</div>
</div>
page1.html
<div class="page1">
<div id="gallery1">slider1</div>
</div>
page2.html
<div class="page2">
<div id="gallery2">slider2</div>
</div>
Upvotes: 0
Views: 181
Reputation: 4288
It happens because the code is executed before the plugin is successfully loaded. So you have to use the callback function in your .load()
method:
Edited: To prevent the reload of the plugin I created a third function to do the functionally. This logic can be improved, but I think you can work so:
$("#div1").on("click", function() {
if( $.fn.touchSlider === undefined ){
$.getScript( "js/jquery.touchSlider.min.js", function() {
loadSlider(2, 2);
});
}
else {
loadSlider(2, 2);
}
});
$("#div2").on("click", function() {
if( $.fn.touchSlider === undefined ){
$.getScript( "js/jquery.touchSlider.min.js", function() {
loadSlider(1, 1);
});
}
else {
loadSlider(1, 1);
}
});
function loadSlider(page_number, gallery_number){
$("#main-content").html("").load("page" + page_number + ".html", function(){
$('#gallery' + gallery_number).touchSlider({
animation: 'js',
mode: 'shift',
offset: 'auto'
});
});
}
Check jQuery .load
documentation.
Upvotes: 1