Create DIV with onMouseOver effect with JS
14,854
Solution 1
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 );
Solution 2
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
}
Solution 3
Use jQuery .hover()
:
$('#myDiv').hover(doSth, doSthElse);
Solution 4
If you just want to display some other element or change the style of the div, you can also use a CSS class:
var div = document.createElement('div');
div.className = "hoverEffect";
Then you can style the the div using the CSS :hover selector. For example:
div.hoverEffect:hover {
color:#fff;
}
div.hoverEffect child {
display:none;
}
div.hoverEffect:hover child {
display:block;
}
Solution 5
I suggest to use .attr()
jquery:
$(myDiv).attr("onMouseOver","doSth()");
$(myDiv).attr("onMouseOut","doSthElse()");
Author by
user2078872
Updated on June 28, 2022Comments
-
user2078872 almost 2 years
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?