CHAPTER 6 DECOUPLED NAVIGATION PATTERN 169 function (Web design course)

CHAPTER 6 DECOUPLED NAVIGATION PATTERN 169 function MonitorLinks( evt) evt = (evt) ? evt : ((event) ? event : null) if( evt) var elem = (evt.target) ? evt.target ((evt.srcElement) ? evt.srcElement : null) if( elem) if( elem.href == “http://www.apress.com/”) { window.alert( “Not allowed on Apress”); return false; } else if( elem.href == “http://www.google.com/”) { window.alert( “Not allowed on Google”); return false; } else if( elem.href == “http://www.slashdot.org/”) { return true; } return false; } In the implementation of MonitorLinks, there is the usual code to retrieve the source E B V N HTML element (elem) and event (evt). If the variable elem is not null, the property elem.hrefis tested. The property is tested against three tests to see which link has been clicked. For the cases of having clicked on apress or google, a window.alert pop-up box appears, indicating that the link cannot be clicked. After the user clicks the OK button, the MonitorLinks function returns a value of false to indicate that the event bubbling should be canceled. Canceling the onclick event causes the navigation to be halted, with the HTML content staying as is. You need to make a mental note that the function MonitorLinks assumes that the elem variable references a link element. The assumption is due to the property reference elem.href, because the href property is applicable only to a link element. It is not a bad thing to assume, but you must remember it because MonitorLinks is a function that captures the click event for all child HTML elements. If there were a button that generated a click event, MonitorLinks would fail and potentially cause undesired side effects. A solution is to use the elem.nodeName property and test whether the source element is a link. From the example, the if statement would be rewritten to the following: if( elem && elem.nodeName == “A”) Another solution is to reference a common property such as id when testing for a specific link identifier. Using the id property is a useful solution because the property is type agnostic and is a unique identifier. The unique identifier is a good way to compare and distinguish HTML elements because there is no possibility of making a by-accident failure. A by-accident failure is illustrated by the following source code: Apress is not allowed // … if( elem.href == “http://www.apress.com/”)
Visit our web design programs services for an affordable and reliable webhost to suit all your needs.

Leave a Reply