Javascript DOM Element class set via mouse event

Description

Javascript DOM Element class set via mouse event

View in separate window


<!DOCTYPE html>

<html>
<head>
   <style type='text/css'>
      .Normal {//w  w  w  .  j  a va  2s  . c om
         font-family: Arial;
         color: blue;
      }
      .Selected {
         font-family: Georgia;
         font-size: larger;
         color: green;
      }
   </style>
   <title>Changing Styles Dynamically</title>
   <script language="JavaScript">
      function ChangeStyles(event)
      {
         // Obtain a reference to the element.
         var ThisElement = document.getElementById(
            event.currentTarget.id);
         
         // Check the event type.
         if (event.type == "mouseover")
         {
            // Change the target element's CSS class.
            ThisElement.setAttribute("class", "Selected");
         }
         else
         {
            ThisElement.setAttribute("class", "Normal");
         }
      }
   </script>
</head>

<body>
   <h1 id="Header" class="Normal">Formatting the Style Tag Directly</h1>
   <p id="P1" class="Normal">Some text to format.</p>
   <p id="P2" class="Normal">Some more text to format.</p>
   
   <script language="JavaScript">
      // Obtain a list of elements that use the <p> tag.
      var ElementList = document.getElementsByTagName("p");
      
      // Process each of these tags in turn.
      for(var i = 0; i < ElementList.length; i++)
      {
         // Add handlers for the mouseover and mouseout events.
         ElementList[i].onmouseover = ChangeStyles;
         ElementList[i].onmouseout = ChangeStyles;
      }
   </script>
</body>
</html>



PreviousNext

Related