How to Register a Domain Name for Your HTML5 and CSS3 Site
How to Use IrfanView’s Built-In Effects for HTML5 and CSS3 Programming
10 Stellar Web Resources for HTML5 and CSS3

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
How to Create a New JavaScript File in Komodo Edit
How to Create Cascading Style Sheets (CSS) Simply and Easily
Checking and Clearing Locally Stored Data with HTML5
Add Attributes to Your HTML5
How to Load jQuery from Google CDN to Use with JavaScript
Advertisement

Inside Dummies.com