How to run a javascript function during a mouseover on a div

Hulk picture Hulk · Jan 5, 2010 · Viewed 106.5k times · Source

How can I get a Javascript function to run when the user mouses over a div tag?

Here is my div tag:

<div id="sub1 sub2 sub3">some text</div>

Answer

Nathan Wheeler picture Nathan Wheeler · Jan 5, 2010

I'm assuming you want to display the welcome when you mouse over "some text".

As a message box, this will be:

<div id="sub1" onmouseover="javascript:alert('Welcome!');">some text</div>

As a tooltip, it should be:

<div id="sub1" title="Welcome!">some text</div>

As a new div, you can use:

<div id="sub1" onmouseover="javascript:var mydiv = document.createElement('div'); mydiv.height = 100; mydiv.width = 100; mydiv.zindex = 1000; mydiv.innerHTML = 'Welcome!'; mydiv.position = 'absolute'; mydiv.top = 0; mydiv.left = 0;">some text</div>

You should NEVER contain spaces in the id of an element.