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);
});
});
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.txtandlink2=>hellouniverse.txt, like this:Then:
That assumes that the
link1orlink2class will be the only class on the element. If that won’t be the case, you may have to massageclassNamea bit before using it to look up the file.Use
data-*attributes.Add a
data-fileattribute to yourlinkelements, e.g.:Then:
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 adata-fileattribute.