Reputation: 1432
I have this set up to load a file into a DIV using the two links in the left DIV but it requires a unique copy of the same JQuery code each time there is a new link.
Is there a way of connecting the file being called and the DIV it is being called from to the link via some kind of variable maybe so that the code has to be included only once?
$(function() {
$(".link1").click(function() {
$(".load_space").load("helloworld.txt", function() {
//Insert contents of file wherever
$(".block1").stop(true, true).animate({ left: -400 }, 200);
$(".block2").stop(true, true).animate({ left: 25 }, 200);
});
});
$(".link2").click(function() {
$(".load_space").load("hellouniverse.txt", function() {
//Insert contents of file wherever
$(".block1").stop(true, true).animate({ left: -400 }, 200);
$(".block2").stop(true, true).animate({ left: 25 }, 200);
});
});
$(".link3").click(function() {
$(".block2").stop(true, true).animate({ left: 450 }, 200);
$(".block1").stop(true, true).animate({ left: 25 }, 200);
});
});
Upvotes: 1
Views: 426
Reputation: 1074295
There are a couple of ways.
Use a map in your code.
You could have a map in your code that tells you that link1
=> helloworld.txt
and link2
=> hellouniverse.txt
, like this:
var map = {
link1: "helloworld.txt",
link2: "hellouniverse.txt"
};
Then:
$(".link1, .link2").click(function() {
var file = map[this.className]; // <=== Assumption here, see below
$(".load_space").load(file, function() {
//Insert contents of file wherever
$(".block1").stop(true, true).animate({ left: -400 }, 200);
$(".block2").stop(true, true).animate({ left: 25 }, 200);
});
});
That assumes that the link1
or link2
class will be the only class on the element. If that won't be the case, you may have to massage className
a bit before using it to look up the file.
Use data-*
attributes.
Add a data-file
attribute to your link
elements, e.g.:
<div class="link1" data-file="helloworld.txt">...</div>
Then:
$(".link1, .link2").click(function() {
var file = $(this).attr('data-file');
$(".load_space").load(file, function() {
//Insert contents of file wherever
$(".block1").stop(true, true).animate({ left: -400 }, 200);
$(".block2").stop(true, true).animate({ left: 25 }, 200);
});
});
or instead of the $(".link1, .link2")
selector, you could just use $("*[data-file]")
or better yet, something a bit more targeted (since selecting purely on an attribute selector is a bit heavy). So perhaps $(".links[data-file]")
for any element with class "links" that has a data-file
attribute.
Upvotes: 1
Reputation: 23542
You can define your function once
var load_fct = function() {
//Insert contents of file wherever
$(".block1").stop(true, true).animate({ left: -400 }, 200);
$(".block2").stop(true, true).animate({ left: 25 }, 200);
}
And reuse it where you need it:
$(".link1").click(function() {
$(".load_space").load("helloworld.txt", load_fct);
});
Upvotes: 1