Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create DIV with onMouseOver effect with JS

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?

like image 789
user2078872 Avatar asked Nov 30 '22 01:11

user2078872


2 Answers

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 );
like image 108
christian314159 Avatar answered Dec 04 '22 11:12

christian314159


Use pure Javascript EventTarget.addEventListener

var myDiv= document.createElement("div");
myDiv.addEventListener("mouseover", mouseOver, false);
myDiv.addEventListener("mouseout", mouseOut, false);
document.body.appendChild(myDiv);
function mouseOver()
{  
   //do something
}

function mouseOut()
{  
   //do something
}
like image 31
Gildas.Tambo Avatar answered Dec 04 '22 11:12

Gildas.Tambo