JavaScript: Link Area


Introduction

Author: Martin Warning
Year: 2007
Updated: 2008
License: Free

Often we create menu's where the link could be a whole area instead of the link text alone. This site's menu is a good example of such a use.

Code

Languages: The following code is an example link area:
<div onclick="window.location.href=('page.html');">
	Some text
</div>

This simply opens a link when clicking anywhere in the <div> area. The <div> can contain links, but it doesn't have to


The following code is another example link area:
<div onclick="window.location.href=(this.getElementsByTagName('a')[0]);" style="cursor:pointer;">
	<a href="page.html">Page</a>
</div>

In this example we add the onclick event to a <div> containing a link. This will allow the user to click anywhere in the <div> to open the link. In the part this.getElementsByTagName('a')[0]); the 'a' represents the XHTML <a> element. The 0 value indicates the first <a> element found inside the <div>. If you would change the value to 1 it would use the second <a> element found inside the <div> as link value. This example requires that you have a link located inside the <div>, but has as advantage that you only write the link once. Also added is the CSS code to show the cursor's link pointer when the mouse is over the <div> so that the user knows that it's a link.



Kiva - loans that change lives
Printed from: http://flyinglowlander.com/ (5/20/2012)
© FlyingLowander.com 2006 - 2012

Visit http://flyinglowlander.com for more XHTML, CSS, ASP and JavaScript examples, templates and tutorials.