jQuery Change Content Plugin

jQuery Swap Content Demo

Hover over the links on the left to observe.

A jQuery plugin to change the content of an element onmouseover of a link or other element is presented on this page. A non-jQuery version of the code also available.

Although the old-school approach to providing this functionality is exceedingly simple, current practices of unobtrusive scripting add considerable complexity to the code, sufficient to consider using jQuery rather than writing the code from scratch. We have done both, just for fun, and for study and comparion.

Instructions

Setup for the code is very similar to the non jQuery version, both very easy.

Script Tags

Include script tags for jquery.js and the content change plugin file:

<script src="js/jquery-min.js" type="text/javascript"></script>
<script src="js/jquery.dw_hoverswapcontent.js" type="text/javascript"></script>

Element for Content Change Display

Include an element for display in your layout and attach a unique id; the default is infoDiv. But you can choose whatever id and element type you like. No need for it to be a div.

Class Names

A class name is attached to elements that have content to display onmouseover: showInfo is the default. A space, then a second class name is added as a pointer to the content for that element. An example link is set up as follows:

<a href="#" class="showInfo Link1">Link 1</a>

Settings and Content

An object literal[1] holds the settings and the data that you wish to display onmouseover. An example:

var content_swap1 = {
    // these are the default values
    // you can leave out or change
    className: 'showInfo',
    displayId: 'infoDiv',
    restoreDefault: true,
    
    // specify content here
    content: {
        Link1: 'Hello there!',
        Link2: 'Say wha?'
        // add as many as you like
        // watch the syntax though!
    }
}

jQuery ready

All of the above is virtually identical to the setup for the non-jQuery version of the code, aside from the JavaScript files included of course. However, when it comes to initializing the code jQuery does things differently, placing everything inside an anonymous function to be invoked when the document is ready:

$(document).ready(function(){
    
    var content = {
        Link1: 'yo',
        // etc.
    }
    
    $( document ).dw_hoverSwapContent(content);
});

As with the other version, you can specify more than one area for content changes to be displayed. A single link can direct changes to both (or even more) display areas. The example in the download file provides more information.

Get the Code - It's Free!

A download file contains the code and example document.

The code is provided free of charge. Donations are appreciated. Please read dyn-web's Terms of Use if you plan to use our code.


  1. See our brief tutorial on Object Literals if you are unfamiliar with their use and structure. ^