Search code examples
javascriptgoogle-books

Google Book Viewer API - can't hide then show


I'm using the Google Book Viewer API to show book previews based on metadata found on the page. This is in a system I don't control, although I can append scripts and markup.

Only some pages contain information about books that have previews available. The book viewer is inside a div which, if the preview isn't found, is empty and looks ridiculous; so my strategy is to hide the div via CSS, then, if a preview is found, change the ID of the div so that it is no longer hidden. If I do that, though, when the div appears, the preview does not show correctly; if you zoom in and out with your browser, it does, but otherwise no.

Here's an example of it working. (I've simplified the script--normally I traverse the page to get the metadata, whereas here I'm just supplying it in a string.) Everything is there except the CSS: https://googledrive.com/host/0BxoVkXnTNNDoV3NpQUtsNDEyaTQ/gbpreview.htm

And here it is with the CSS, not working: https://googledrive.com/host/0BxoVkXnTNNDoV3NpQUtsNDEyaTQ/gbpreview2.htm

Anyone know how I might fix this, or can you think of an alternative strategy to achieve what I'm looking for?

And here is the code:

<style type="text/css">#GoogleBooksPreview {display: none;} </style>
<div id="GoogleBooksPreview">
    <div id="viewerCanvas" style="height: 600px;">
    </div>
</div>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">var gbsWidget = document.getElementById('GoogleBooksPreview');
function gbsFound() {
    gbsWidget.id = 'gbsFound';
}
function initialize() {
    var viewer = new google.books.DefaultViewer(document.getElementById('viewerCanvas'), {
        showLinkChrome: false
        });
   viewer.load(['ISBN:9780596805524', 'OCLC:502415271'], null, gbsFound);
    }
    google.load("books", "0");
    google.setOnLoadCallback(initialize);
</script>

Solution

  • It looks like the recommended way to handle this is to hide the div on failure, rather than unhide the div on success, see here. I'm guessing this is necessary because the viewer needs to know the height of the canvas (which it won't have if the container is hidden).

    See a working example here: http://jsfiddle.net/67pay4r2/.

    Or without adding a hidden class like: http://jsfiddle.net/67pay4r2/1/.

    I have added a hidden class to the widget div, which is removed when the initialize function starts, and then added back if the viewer load fails. This will prevent users with JS disabled from seeing the div.