Reputation: 1432
I'm using JQuery.load() to pull the contents of a file into a webpage. The javascript to pull this off is in a separate .js file to keep things tidy.
/* Pulls in file contents */
$(function() {
$('.div').load('file.html');
});
However, when the file is pulled in the jquery animation I am using to crossfade images - the code for which is also in the .js file - doesn't work.
/* Crossfade code */
$(function(){
$(".appearing-image img").css("opacity",0).fadeTo(300, 0);
$(".appearing-image img").mouseover(function () {
$(this).fadeTo(200, 1);
});
$(".appearing-image img").mouseout(function () {
$(this).fadeTo(200, 0);
});
});
I found out that the only way to get it to work was to include it in the .load() code.
/* Pulls in file contents and executes animation */
$('.div').load('file.html', $(function(){
/* Crossfade images */
$(".appearing-image img").css("opacity",0).fadeTo(300, 0);
$(".appearing-image img").mouseover(function () {
$(this).fadeTo(200, 1);
});
$(".appearing-image img").mouseout(function () {
$(this).fadeTo(200, 0);
});
});
});
That works.
However, elsewhere on the page other images won't crossfade unless the code is also included by itself, separate from the .load() which means I am now including the code twice.
Is there anyway to avoid this?
Upvotes: 0
Views: 321
Reputation: 2579
You may use
$(window).bind('setup', function() {
//code
});
to load something before the document is ready
Upvotes: 0
Reputation: 7032
Use an external function, such as something like crossfade()
/* Crossfade code */
function crossfade(){
$(".appearing-image img").css("opacity",0).fadeTo(300, 0);
$(".appearing-image img").mouseover(function () {
$(this).fadeTo(200, 1);
});
$(".appearing-image img").mouseout(function () {
$(this).fadeTo(200, 0);
});
}
/* Pulls in file contents and executes animation */
$('.div').load('file.html', function(){
/* Crossfade images */
crossfade();
});
Upvotes: 2