Advertisement
Online Test Banks
Score higher
See Online Test Banks
eLearning
Learning anything is easy
Browse Online Courses
Mobile Apps
Learning on the go
Explore Mobile Apps
Dummies Store
Shop for books and more
Start Shopping

How to Build Dynamic HTML Elements in JavaScript

One of the building blocks for creating special effects for any page is the ability to make dynamic HTML changes to the page. For example, you may want to create a special effect for the selected element as shown in the following example.

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");
  }
}

This code accepts an event as input. The code obtains a reference to the element provided by the Event object. It then checks the event.type property to determine what type of event has happened (either a mouseover or a mouseout). The type of event determines what sort of formatting the element uses.

Of course, it would be handy to provide some sort of automation for assigning an event handler for the onmouseover and onmouseout events. The following code performs this task for you:

<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>

This is another variant of interacting with a group of elements that use the same tag — the <p> tag in this case. The code obtains an array of these elements by calling getElementsByTagName(). It then assigns the ChangeStyles() function to the onmouseover and onmouseout properties of each element. The result is that each <p> tag on the page reacts when you hover the mouse over it.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win an iPad Mini. Enter to win now!