Changing Content OnMouseover or OnClick

Try the links in the demo below to see the content change. JavaScript available here provides the means to change the content of an element unobtrusively, in accordance with current practices.

Swap Content OnMouseover or OnClick

Hover over the links on the left or click the links on the right to observe the Change Content JavaScript in action.

First we describe the old-fashioned way of performing this very basic task.

How It Used To Be Done

If you don't mind using event handler attributes in your html, the code is simple as can be. Here is a function that changes the innerHTML of any element; just pass the element's id and the string content to display:

function changeContent(id, msg) {
  var el = document.getElementById(id);
  if (id) {
    el.innerHTML = msg;

The following is an example link for onmouseover. The changeContent function is called again onmouseout, restoring the original content which is held in a variable (orig):

<a href="." onmouseover="changeContent('infoDiv', 'New content here')" 
  onmouseout="changeContent('infoDiv',orig)">Hover here</a>

The changeContent function can be applied onclick too:

<a href="#" onclick="changeContent('infoDiv',msg2); return false">Click here</a>

This code works fine in virtually all browsers in current use. Nonetheless, this approach has fallen out of favor as current practices dictate separation of concerns; that is, code (and styles) should be kept out of the page markup.

Changing Content with Unobtrusive Code

The new approach is much more involved than the old. The event handling code, helper functions to locate elements with specified classes, functions to help determine whether the mouse has actually left the element - these all add to the code's challenges. This is why we also coded a jQuery plugin version, for comparison and for fun!

The documentation provides information for setup of the Change Content JavaScript. Setup is easy and keeps your markup clean. A download file provides examples demonstrating both the old and new approaches.

Back to top