Changing Content OnMouseover or OnClick

On this page we provide JavaScript that changes the content of an element onmouseover or onclick. Try the links in the demo below to see. This script updates an old HTML event handler attribute based JavaScript to unobtrusive event handling.

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.

How It Used To Be Done

If you don't mind using event handler attributes in your HTML, the code is very brief and simple. 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 Event Handling

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. No worries though. Setup is easy and keeps your markup clean. The documentation shows you how. A download file provides examples demonstrating both the old and new approaches.