How to create a mouse-over image for a wordpress post

Posted by on Jan 11, 2011 in code, how to | No Comments

This comes from a nice tutorial that you can find here at: More Than A Maths Teacher.
 

 
You will need to add a javascript file to the root folder of your current wordpress theme. Code is below. Note the the images I used for the mouse-over are named image.png and image_over.png. For this particular script to work, your images must be names image.png and image_over.png ( “image” stands for whatever you want, and can be replaced). If you want to use another file format, than png, you must edit the code.

jQuery(function($) {
$(document).ready(function() {

		// Preload all rollovers
		$(".hoverlink img").each(function() {
			// Set the original src
			rollsrc = $(this).attr("src");
			rollON = rollsrc.replace(/.png$/ig,"_over.png");
			$("<img>").attr("src", rollON);
		});

		// Navigation rollovers
		$(".hoverlink a").mouseover(function(){
			imgsrc = $(this).children("img").attr("src");
			matches = imgsrc.match(/_over/);

			// don't do the rollover if state is already ON
			if (!matches) {
			imgsrcON = imgsrc.replace(/.png$/ig,"_over.png"); // strip off extension
			$(this).children("img").attr("src", imgsrcON);
			}

		});
		$(".hoverlink a").mouseout(function(){
			$(this).children("img").attr("src", imgsrc);
		});

	});
});

Nextyou will need to add the following code to your head.php file, somewhere between the tags.

 <?php
       wp_enqueue_script('jquery');
       wp_enqueue_script('jquery-core-ui');
       wp_enqueue_script('jquery-tabs-ui');
       wp_enqueue_script('hoverlink', get_bloginfo('template_directory').'/rollover.js');
       wp_head();
    ?>

Finally use this format to the post to add the images:


<div class="hoverlink">
<a href="http://www.anysite.com"><img src="http://www.anysite.com/pat/to/your/image.png" border="0" alt="mouse-over" width="200" height="100" /></a></div>

Email this to someoneTweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on StumbleUponShare on RedditDigg this

Leave a Reply