Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I\'m proficient with HTML and CSS but I\'m still pretty shaky when it comes to J

ID: 647377 • Letter: I

Question

I'm proficient with HTML and CSS but I'm still pretty shaky when it comes to Javascript. That said, I've been able to build a site using the Internet Archive Book Reader, which relies on reader.js

Here's a copy of one of my versions of reader.js https://gist.github.com/dylan-k/ed4efed2384e221d46cc

It's a good site, but I find I have to repeat things a lot. Basically, I have one copy of reader.js for every page/book featured on the site. It seems there must be a better way. I re-use the script, making copies, just so that I can change lines 28, 80, 83, 84.

Is there a way I could include just one copy of reader.js and then use a <script> tag to define these 4 lines for the individual pages?

Explanation / Answer

As you've noticed, the basic problem is that - as written - that script isn't reusable. It's hardcoded for a specific case. There's no straightforward way to pass in different settings on different pages.

So you'll need to modify that script to make it reusable.

There are any number of ways you could do that, but here's one that involves minimal modifications to the original code:

<script>

// Define a global object containing the BookReader parameters for this
// page. Make sure this appears in your markup *before* the <script> tag
// that loads reader.js.
var BookReaderParams = {
urlStart: "/exhibitions/bythebook/book8/W922/W922_",
urlEnd: "_sap.jpg",
numLeafs: 328,
bookTitle: "Liber Amicorum (Friendship Book) of Joannes Carolus Erlenwein",
bookUrl = "http://thewalters.org/exhibitions/bythebook/book8/"
};
</script> <script src="reader-modified.js"></script>

Then, change the following lines in your modified version of reader.js:

Line 28 becomes:

var url = BookReaderParams.urlStart + leafStr.replace(re, imgStr) + BookReaderParams.urlEnd;

Line 80 becomes:

br.numLeafs = BookReaderParams.numLeafs;

And lines 83 and 84 become:

br.bookTitle = BookReaderParams.bookTitle; br.bookUrl = BookReaderParams.bookUrl;

This isn't how I would structure things if I were writing this functionality from the ground up; there are much cleaner patterns for reusable code. However, given the codebase you're working with, this is a quick-and-dirty way to inject values into the script without needing a separate copy of reader.js for every page.