I have a very simple links page for sharing links on Instagram and other social media. It currently looks like this:
I like to add a little flair throughout the year though and with Thanksgiving being tomorrow, I thought, "why not give thanks to those who visit my links page by showing them one of the most beautiful birds there is, the Wild Turkey?".
I know, its breathtaking. After you take a moment to recover, let's go through the code.
We start with a basic CSS animation. For the HTML there is a <div class="turkey"> that we will be manipulating. Let's set the height and width of the div and the background image to the .png file of the turkey.
The CSS property animation-delay only applies to the first iteration of an animation so to create a delay before each turkey entrance, I opted to position the turkey further to the left at the start of each iteration.
This all looks pretty good but there are two problems:
The speed at which the turkey trots depends on the width of the browser window since the animation duration is a set value
The width of the path the turkey trots is not updated when the user resizes the browser window with some browsers. For animations, the relative values (vw) get converted to absolute values but do not automatically get updated when the window resizes.
We're going to need a little bit of Javascript for this one.
I wanted the turkey to trot a certain number of pixels per second, so we can calculate the animation duration by dividing the window width (px) by pixels per second (px/s).
The documentElement property allows you to programmatically set style properties on the root element of the document, the CSS equivalent of:
By modifying the value of the animation-duration property this causes all of the animation values to be recalculated on a window resize so this takes care of both of our problems: maintaining a constant turkey trot speed and making sure the turkey trots across the entire screen.
When the page loads, we'll instead run the createTurkeyContainer function and append the adjustTurkeyAnimation to the end of the createTurkeyContainer function.
Now the turkey can be added to the page by loading the turkey CSS and JS files via an HTML snippet.
My links page is an Eleventy site using the Nunjucks templating language, so to include the code I just add the following code to the <head> of my links page: