APIs for Librarians

Helping you to help yourself in helping your patrons ;)

Display a Random LibGuide Link on Page Load


Description

This code will pull a random guide from your system’s published guides and display it as a simple link. Also, there’s a button that will regenerate the randomized guide.

Screenshot

Display a Random LibGuide Link on Page Load screenshot

More details

The API call, which is written in jQuery, will send your authorization key along with some pieces of information that will tell LG to only return JSON data about guides from a single subject or subjects.

Once that data is returned we pull out the title of the guide and also its URL and place those pieces into a link element. The jQuery will then enumerate through each JSON entry doing the same thing again and again until complete. You might have a list of 3 items or 300, it doesn’t matter.

You link up the jQuery and your actual HTML using a specific ID name in your HTML, assigned to an <a>.

Pressing the button will re-run everything and display a new link.

The Code

HTML

1
2
3
4
5
<div id="random-guide-container">
    <h4>Have you considered?</h4>
    <div id="foo"></div>
    <input type="button" id="btn" value="Try Another" />
</div>

CSS

1
2
3
#random-guide-container {font-family: 'Martel', serif; font-size: 1.2em;text-align:center;}
#random-guide-container #btn {font-size: .7em;}
#btn { margin-top: .7em; display: inline-block; line-height: 1.25; text-align: center; vertical-align: middle; background: #FFF; border: 1px solid #777; padding: .5rem 1rem; border-radius: .25rem; }

JavaScript/jQuery

Notes for implementation:
The code itself:
1
2
3
4
5
6
7
8
9
var apis4librarians_randomLibguide = function(){$(document).ready(function () {
var getRandomGuide = function () {
$.getJSON('https://lgapi-us.libapps.com/1.1/guides?site_id=foo1&key=foo2&status=1', function (result) {
var entry = result[Math.floor(Math.random() * result.length)];
var randomGuide = '<a href="' + entry.url + '">' + entry.name + '</a>';
$('#foo').html(randomGuide);
}); };
getRandomGuide();
$('#btn').click(function () {getRandomGuide()}); });}();