ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

A Beginner JavaScript Tutorial Series: Accessing the HTML DOM (Document Object Model) With JavaScript (Part II)

Updated on March 24, 2014

What Was Covered in Part I & What to Expect in Part II

In part one of this two part tutorial, A Beginner JavaScript Tutorial Series: Accessing the HTML DOM (Document Object Model) With JavaScript (Part I) The HTML DOM (Document Object Model) was introduced and we demonstrated several methods for accessing HTML content and modifying it. The examples in that tutorial demonstrate the technical features which one must understand, but they lacked the "flash" of seeing a web page change dynamically. In this tutorial on events we will see some of that flash because events will trigger pages updates. Also, we will add in CSS styling is some of our examples.

Just a Warm Up for Today: JavaScript Changing an Image

In this example, we change the self-portrait of Rembrandt with that of Cardinal Wolsey. If anything, it demonstrates that there is really no "magic" involved. We locate the new picture by invoking the getElementById() method and the subtitution is performed by doing the assignment to the src property. In this example we avoid distortion because the original Rembrandt image was 439px by 599px while the Cardinal is 444px by 599px. If the images sizes were much different you would really want to change the width and height craracteristics as well.

A Simple Image Substitution Performed by JavaScript

There is no magic with substituting images with JavaScript. You use the same method, getElementById, you just access and modify a different property name.
There is no magic with substituting images with JavaScript. You use the same method, getElementById, you just access and modify a different property name.

Change Style Elements for Text in JavaScript

The following snapshot illustrates changing multiple properties. My using the inspect element for the unchanged, identical heading we see the attributes taken on and those overridden specific to the h2 element defaults.

Modifying a Header Element with JavaScript

We started with defining two identical  elements and modified the CSS styling for one of theme.
We started with defining two identical elements and modified the CSS styling for one of theme.
This is looking at the the page by right clicking on it and choosing inspect element. Not how the new CSS attributes are included in the text. Also, note the "strike through" on the font-size.
This is looking at the the page by right clicking on it and choosing inspect element. Not how the new CSS attributes are included in the text. Also, note the "strike through" on the font-size.

Changing HTML Content When An Event Occur

This is where we see pages change dynamically, when an event occurs. The types of events which can occur (and what follows is just a sampling) are:

Input Events

onchange - a user changes the content of an input field

onfocus - an input field gets focus

onkeydown - a user is pressing/holding down a key

onkeyup - the user releases a key

onreset - a user clicks the reset button

onselect - input text is selected

onsubmit - a user clicks the submit button

Mouse Events

onmousedown/onmouseup - pressing/releasing a mouse button

onmousemove/onmouseout - moving the mouse pointer over/out of an element

Click Events

onclick - button is clicked on

dblclick - a text is double-clicked

Load Events

onerror - an error occurs when loading an image

onload - the page/image has been loaded

onresize - the browser window is resized

onunload - the browser closes the document


A Click Event: When an "onclick" Event Occurs

The following snapshot shows a change in the CSS style for the header element whwn the button is clicked. The coloris changed from the defualt color black to blue.

An onclick Example

Notice how this is achieved.: The onclick assignment specified getting the element by id and performing a style assignment to the color blue.
Notice how this is achieved.: The onclick assignment specified getting the element by id and performing a style assignment to the color blue.

An onclick Example: Calling a JavaScript Function

This is another onclick example. It differs from the first in that instead of invoking the getElementById() method directly in the statement, we invoke a function which does the processing. This can sometimes make your code look a little less "busy". For example, if we were changing an image here with multiple parameters of src,width, and height is cleaner, clearer (and less error prone) to read multiple statements in a function rather than an elongated string following the onclick=.

Using an Invocation of a JavaScript Function to Perform the Change

Invoking a JavaScript function to actually perform a change is a good way to make your code more readable and less error prone. Notice how the text in the background is changed to Ouch!.
Invoking a JavaScript function to actually perform a change is a good way to make your code more readable and less error prone. Notice how the text in the background is changed to Ouch!.

Utilizing a JavaScript Built-In Function

There are a number of handy JavaScript functions which you can use in your web pages. The Date() function is one of them. When building a web page you could simply run a script to display the time the page was loaded. In other cases you might want to use JavaScript to set and refresh a simple digital clock. Simple options are available and by styling you can make them as simple or involved as you want.

Displaying Day and Time by Invoking a Built-In Function

In this example we invoke our own function displayDate which simply makes an assignment to the "empty" paragraph demo. This allows you to decide on the placement of the information within the page.
In this example we invoke our own function displayDate which simply makes an assignment to the "empty" paragraph demo. This allows you to decide on the placement of the information within the page.

An onload Example

This is an example of an onload event. The event handler in this case checks to see if cookies are enabled in the browser. An alert box indicates the result of making that determination.
This is an example of an onload event. The event handler in this case checks to see if cookies are enabled in the browser. An alert box indicates the result of making that determination.

A JavaScript onload Example

In this example, we check to see if cookies are enabled in the browser. This example illustrates something more and something we have been taking for granted.

When we perform a document.write("Something"); What are we really doing? In terms of the OOP model, document is really an object and it is the entire writable area of the screen or web page. write is a method associated with the object.

Now, notice carefully at the current example, we have never seen the object "navigator" before. That is because it is not part of the HTML DOM but rather is a part of the BOM, Browser Object Model which we will be discussing in the next tutorial.

A mouse Event Handler Example

In this example we look at the two events which occur. When we mouse over the rectangle the code changes. Then when we leave the rectangle it changes back to the original text. This is the general case for "mousing"

A mouseover/mouseout Example

This is about the simplest onmouseover/onmouseout example one can find. It simply toggles the text in the box. Naturally, one could add more features such as changint the box size or the box color.
This is about the simplest onmouseover/onmouseout example one can find. It simply toggles the text in the box. Naturally, one could add more features such as changint the box size or the box color.

The HTML DOM is a Hierachy

Wrap Up and What's Next

In this tutorial we looked at modifying the HTML DOM when an event occurs. The code which makes the change is called an event handler. Anything that you could possibly do in interacting with a web page could probably result in some coding for the event. We indicated that there are four types of events: when pages are loaded and unloaded, when there is a mouse action, when an input value is entered to changed, and when a button is clicked.

Thereis some other items related to the HTML DOM such as nodes and nodelists which we will defer until we have had the opportunity to study JavaScript arrays.

We alluded to the Browser Object Model (BOM) in this tutorial in that we used it to determine wheteher cookies were enabled. Unfortunately the BOM is not like the DOM. There is no uniform adopted standard. So, it must be used with care. Many of the methods which can be used in the BOM have been adopted by the major browsers (e.g. Chrome, Internet Explorer, Safari, Opera, etc.) but more on this subject in the next installment.

Till then experiment with the enevnts we didn't get to illustrate. The list in this tutorial is a good place to start ferreting out information.

Was This Tutorial Easy to Follow?

Cast your vote for Was the information presented clear and concise?
working

This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://corp.maven.io/privacy-policy

Show Details
Necessary
HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
LoginThis is necessary to sign in to the HubPages Service.
Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
AkismetThis is used to detect comment spam. (Privacy Policy)
HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
Features
Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
MavenThis supports the Maven widget and search functionality. (Privacy Policy)
Marketing
Google AdSenseThis is an ad network. (Privacy Policy)
Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
Index ExchangeThis is an ad network. (Privacy Policy)
SovrnThis is an ad network. (Privacy Policy)
Facebook AdsThis is an ad network. (Privacy Policy)
Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
AppNexusThis is an ad network. (Privacy Policy)
OpenxThis is an ad network. (Privacy Policy)
Rubicon ProjectThis is an ad network. (Privacy Policy)
TripleLiftThis is an ad network. (Privacy Policy)
Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
Statistics
Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
ClickscoThis is a data management platform studying reader behavior (Privacy Policy)