Create DIV with onMouseOver effect with JS

user2078872 picture user2078872 · Jun 30, 2014 · Viewed 12.5k times · Source

I would like to create a DIV element via Javascript, but it should have a onMouseOver effect.

so I know what the tags look like in HTML:

<div onMouseOver="doSth()" onMouseOut="doSthElse()"> </div>

and I know how to create my DIV:

var myDiv= document.createElement("div");
//style settings
document.body.appendChild(myDiv);

but how do I create the effect in Javascript code?

Answer

christian314159 picture christian314159 · Jun 30, 2014

Without jQuery, this is what you want:

var myDiv = document.createElement('div');

myDiv.onmouseout  = doSth;
myDiv.onmouseover = doSthElse;
// with doSth & doSthElse being functions you defined somewhere else already
// otherwise you can assign a function here:
// myDiv.onmouseout = function(){};

document.body.appendChild( myDiv );