How to add mouse over event listener for HTML element in Javascript

Mouse over event

The following code uses the mouse over and mouse out event to change the style.

Example


<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
p {<!--   w w  w .j av a  2s  .  c  om-->
  background: gray;
  color: white;
  padding: 10px;
  margin: 5px;
  border: thin solid black
}
</style>
<script type="text/javascript">
  function handleMouseOver(elem) {
    elem.style.background = 'white';
    elem.style.color = 'black';
  }
  function handleMouseOut(elem) {
    elem.style.removeProperty('color');
    elem.style.removeProperty('background');
  }
</script>
</head>
<body>
  <p onmouseover="handleMouseOver(this)"
    onmouseout="handleMouseOut(this)">
    This is a test. 
  </p>
  <p onmouseover="handleMouseOver(this)"
    onmouseout="handleMouseOut(this)">
    This is a test. 
  </p>
</body>
</html>

Click to view the demo





















Home »
  Javascript »
    Javascript Reference »




Array
Canvas Context
CSSStyleDeclaration
CSSStyleSheet
Date
Document
Event
Global
History
HTMLElement
Input Element
Location
Math
Number
String
Window