I was looking for a plugin that could take an image and put it fullscreen as a background on this blog. But I didn’t immediately find one, so I created one myself. I looked at the code in the google home page and started with the Hello Dolly plugin as a base template. It is just an <img> tag that is dynamically resized using jQuery. Here is the full source:
<?php /** * @package Full screen background * @version 0.1 */ /* Plugin Name: Full screen background Plugin URI: http://www.trappers.tk/share/fullbg.tar.gz Description: Full screen background, like the google home page Author: Jeroen Trappers Version: 0.1 Author URI: http://blog.trappers.tk */ function wp_full_bg() { ?> <img id="wpfullbg" src="http://www.example.org/wallpaper.png" > <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script> <script type="text/javascript" language="javascript"> $(function() { fullbg(); $(window).resize(fullbg); }); function fullbg() { var imgw = $('#wpfullbg').width(); var imgh = $('#wpfullbg').height(); var vpw = $(window).width(); var vph = $(window).height(); var imgratio = imgw / imgh; var viewportratio = vpw / vph; var w = vpw; var h = vph; if( viewportratio > imgratio ) { // screen is wider than picture -> increase the heigth of the picture; h = w / imgratio; } else { w = h * imgratio; } $('#wpfullbg').css( { 'left': '0px', 'width': w, 'height': h, 'z-index': '-2', 'top' : '0px', 'position' : 'fixed', 'opacity' : '0.999999999' } ); } </script> <?php } add_action( 'wp_footer', 'wp_full_bg' ) ?>
This wordpress plugin is quite simple. It defines a function wp_full_bg
which will be called by the wordpress system on the action wp_footer
. That’s what you can see in the final line of code. The actual code of the php-function is quite simply outputting the html and javascript.
The first thing I do is create an image with a <img>
tag.
Next I import the jQuery library from the Google CDN.
Now comes the real work: I use jQuery to wait for the document to be loaded. Then I call the javascript function fullbg
. I also set up a jQuery event handler to listen for changes in the size of the window with the resize
function.
In the fullbg
function I first find the image and get it’s height and width. I do the same for the window. Then I use the size of the window to set to size of the image using an inline css style that I apply dynamically with the jQuery css
function. In between I make sure to keep the original aspect ratio of the image, and smartly resizing it to always fully fit the window.
In the style, also the position and z-index are changed, so that the image is positioned underneath the content as a wallpaper or background.
I published the plugin on wordpress.org, so it should become available directly from the wordpress admin console soon. But if you can’t wait, you can download it here or here as well.
Leave a Reply