The "Recipe of the day" gadget is an advanced gadget which uses only public available, well documented methods. It reads recipes from an external XML source and displays one of them at a time. The user can navigate through all recipes in the gadget. The code uses one simple binding and displays most of its content using the innerHTML method which makes it easy to understand for traditional web developers.
The recipe database contains more than 1000 recipes, split into 4 different categories. Because the size of the xml file containing 1000 recipes is way too big to load on every page load and we have to show them in a completely random order, the gadget uses some simple functionality to load recipes in the background.
This works as follows:
- The XML export script returns only 10 completely random recipes.
- At the beginning or when the user switches the category, the gadget starts from scratch and loads 10 recipes into an array.
- Every time the user wants to see a new recipe, the gadget increases the index of the active recipe in the array.
- Whenever there are less than 5 recipes in the array, the gadget starts a download of 10 new random recipes in the background.
- When the download is finished, the gadget adds the new recipes to the array. If one of the new recipes is already in the array, it is ignored.
- When we can't add one of the 10 recipes because we already have all of them, we assume that the user has seen a large part of the recipes, clear the array and start from scratch.
This solution does not guarantee that the user sees every recipe, but there is a very big chance that there should be enough recipes before an old one gets repeated.
There is a simple fade effect which is shown whenever the user switches recipes. The DOM element containing the last recipe gets copied and the new recipe replaces the original one. Using z-index in CSS, the copied element is shown over the new recipe. With a simple JavaScript function, the opacity of the copied recipe gets reduced step by step. When the opacity reaches 0%, the copy is removed from the DOM. In case the user switches through recipes very fast, the "change requests" are queued.