<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>JavaBeat &#187; JavaScript</title>
	<atom:link href="http://www.javabeat.net/category/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.javabeat.net</link>
	<description>Java Technology News</description>
	<lastBuildDate>Fri, 24 May 2013 01:32:07 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Photo Viewer using JavaScript</title>
		<link>http://www.javabeat.net/2013/04/photo-viewer-javascript/</link>
		<comments>http://www.javabeat.net/2013/04/photo-viewer-javascript/#comments</comments>
		<pubDate>Mon, 29 Apr 2013 01:03:17 +0000</pubDate>
		<dc:creator>Suresh Mohan</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=7129</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>HTML has a separate element for image display. This will display the image in a specific region of the page. If we want to add multiple pictures and view it one at a time, then HTML does not have any such tag. We need to build our own design for that. This is a JavaScript [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><a id="dd_start"></a><p>HTML has a separate element for image display. This will display the image in a specific region of the page. If we want to add multiple pictures and view it one at a time, then HTML does not have any such tag. We need to build our own design for that. This is a JavaScript code which will facilitate a new design to display images in a web page.</p>
<p>We have navigation buttons namely back and next to view the various pictures and an exit button to exit this window and view the page.Let us first see how we need to use this java script functionality in the web browser.</p>
<pre class="brush: java; title: ; notranslate">
&lt;div id=&quot;imageViewer&quot;&gt;&lt;/div&gt;
&lt;a href=&quot;#&quot; onclick=&quot;showImage('Gallery/Mangalore',101)&quot;&gt;Mangalore&lt;/a&gt;
&lt;br/&gt;
&lt;a href=&quot;#&quot; onclick=&quot;showImage('Gallery/Sceneries',101)&quot;&gt;Sceneries&lt;/a&gt;
</pre>
<p>First step is that we need to create is a div element. This element must be named as imageViewer. Note that no other name shall be used here, as our script can identify only this name. To specify various links to be used, we can add anchor elements which would invoke the showImage script functions. Two parameters, namely the image folder path and the first image name must be passed. Note that the name of the image can be only numbers between 101 and 999. And the extension of the file must be JPG in caps. For example 104.JPG.</p>
<p style="text-align: center;"><a href="http://www.javabeat.net/wp-content/uploads/2013/04/JS_PV.jpg"><img class="aligncenter  wp-image-7130" alt="JS_PV" src="http://www.javabeat.net/wp-content/uploads/2013/04/JS_PV.jpg" width="431" height="307" /></a></p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>Once this is done, we are done for making our viewer. The photo viewer code looks as below.</p>
<pre class="brush: java; title: ; notranslate">
&lt;script type=&quot;text/javascript&quot;&gt;
imageName=0;
folderName='empty';
arrows=true;

function showImage(folder,file) {
	imageName=file;
	folderName=folder;
	displayDivision();
	displayImage();
}

function changeImageNext() {
	imageName++;
	displayImage();
}

function changeImageBack() {
	imageName--;
	displayImage();
}

function displayDivision() {

	if(arrows) {
		arrows=false;

		//create a outer image division and set its style properties
		outerImageDiv = document.createElement('DIV');
		outerImageDiv.id='outerImageDiv';
		outerImageDiv.style.position='fixed';
		outerImageDiv.style.width='100%';
		outerImageDiv.style.height='100%';
		document.getElementById(&quot;imageViewer&quot;).appendChild(outerImageDiv);

		//create a table element and set its style properties
		table = document.createElement('table'); //table tab
		table.id='imageTable';
		table.align='center';
		table.frame='box';
		table.style.backgroundColor='#F0F0F0';

		//create a table body element
		tbody=document.createElement('tbody'); //tbody  tbo

		//create the first row of the table.
		firstRow=document.createElement('tr');  //row

		//create the first cell of first row and align it
		firstCellRow1=document.createElement('td');  // cell
		firstCellRow1.align='left';
		//populate the elements of the firstCellRow1
		backSpan = document.createElement(&quot;span&quot;);
		backSpan.id='backSpan';
		backSpan.style.border='1px solid #C8C8C8';
		backSpan.onclick=function() {changeImageBack();};
		backSpan.appendChild(document.createTextNode(' BACK '));
		firstCellRow1.appendChild(backSpan);
		firstRow.appendChild(firstCellRow1);

		//create the second cell of first row and align it
		secondCellRow1=document.createElement('td'); //cell
		secondCellRow1.align='center';
		//populate the elements of the secondCellRow1
		exitSpan = document.createElement(&quot;span&quot;);
		exitSpan.id='exitSpan';
		exitSpan.style.border='1px solid #C8C8C8';
		exitSpan.onclick=function() {removeDivision();};
		exitSpan.appendChild(document.createTextNode(' EXIT '));
		secondCellRow1.appendChild(exitSpan);
		firstRow.appendChild(secondCellRow1);

		//create the third cell of first row and align it
		thirdCellRow1=document.createElement('td');
		thirdCellRow1.align='right';
		//populate the elements of the thirdCellRow1
		nextSpan = document.createElement(&quot;span&quot;);
		nextSpan.id='nextSpan';
		nextSpan.style.border='1px solid #C8C8C8';
		nextSpan.onclick=function() {changeImageNext();};
		nextSpan.appendChild(document.createTextNode(' NEXT '));
		thirdCellRow1.appendChild(nextSpan);
		firstRow.appendChild(thirdCellRow1);

		//append the first row in the table body
		tbody.appendChild(firstRow);

		//create the second row of the table.
		secondRow=document.createElement('tr');

		//create the first cell of first row, align it and span
		firstCellRow2=document.createElement('td');
		firstCellRow2.align=&quot;center&quot;;
		firstCellRow2.colSpan='3';

		//populate the elements of the first cell in row 2

		//create and set style for the image division
		imageDiv = document.createElement('DIV');
		imageDiv.id='imageDiv';
		imageDiv.style.backgroundColor='#F0F0F0';
		imageDiv.style.width ='700px';
		imageDiv.style.height ='500px';

		//create and append an image element to the image division
		image = document.createElement(&quot;IMG&quot;);
		image.id='myImages';
		imageDiv.appendChild(image);

		firstCellRow2.appendChild(imageDiv);
		secondRow.appendChild(firstCellRow2);

		//append the second row in the table body
		tbody.appendChild(secondRow);

		//append the table body in the table
		table.appendChild(tbody);

		//append the table to the oter image division
		document.getElementById('outerImageDiv').appendChild(document.createElement('br'));
		document.getElementById('outerImageDiv').appendChild(document.createElement('br'));
		document.getElementById('outerImageDiv').appendChild(table);
	}

	document.getElementById('outerImageDiv').style.visibility='visible';
}

function displayImage() {
	//create a new image element and set the style for it
	newImage = document.createElement(&quot;IMG&quot;);
	newImage.src =folderName+&quot;/&quot;+imageName+&quot;.JPG&quot;;
	newImage.id='myImages';
	newImage.style.width = '700px';
	newImage.style.height ='500px';
	newImage.onerror=function() {noImagesToDisplay();};

	//replace the old image with the new image.
	oldImage = document.getElementById('myImages');
	document.getElementById('imageDiv').replaceChild(newImage, oldImage);
}

function removeDivision() {
	document.getElementById('outerImageDiv').style.visibility='hidden';
	alert('Thanks for viewing');
}

function noImagesToDisplay() {
	document.getElementById('outerImageDiv').style.visibility='hidden';
	alert('no images to display');
}
&lt;/script&gt;
</pre>
<p>Some of the operations that this script supports are next navigation, which takes to the next picture in the folder. back navigation which takes to the previous photo in the folder. The exit will exit from the viewer into the html page. On exit an alert message specifying &#8220;thanks for viewing&#8221; shall be shown to the user. If there are no more pictures, then &#8220;no images to display&#8221; alert message shall be displayed to the user.</p>
<p>We are all set. Now try to open the web page in your browser and click on the links. You shall get an amazing new window open in which your image will be displayed. Moreover we also have some navigation features which make our photo viewing experience great.</p>
<div class='dd_outer'><div class='dd_inner'><div id='dd_ajax_float'><div class='dd_button_v'><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="http%3A%2F%2Fwww.javabeat.net%2Fcategory%2Fjavascript%2Ffeed%2F" send="false" show_faces="false"  layout="box_count" width="50"  ></fb:like></div><div style='clear:left'></div><div class='dd_button_v'><script type='text/javascript' src='https://apis.google.com/js/plusone.js'></script><g:plusone size='tall' href='http://www.javabeat.net/category/javascript/feed/'></g:plusone></div><div style='clear:left'></div><div class='dd_button_v'><a href="http://twitter.com/share" class="twitter-share-button" data-url="http://www.javabeat.net/category/javascript/feed/" data-count="vertical" data-text="JavaScript" data-via="javabeat" ></a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div style='clear:left'></div><div class='dd_button_extra_v'><script type="text/javascript">jQuery(document).load(function(){ stLight.options({publisher:'bab47279-62c9-46af-addc-79fd1fe8fee0'}); });</script><div class="st_email_custom"><span id='dd_email_text'>email</span></div></div><div style='clear:left'></div><div class='dd_button_extra_v'><div id='dd_print_button'><span id='dd_print_text'><a href='javascript:window:print()'>print</a></span></div></div><div style='clear:left'></div></div></div></div><script type="text/javascript">var dd_offset_from_content = 44; var dd_top_offset_from_content = 0;</script><script type="text/javascript" src="http://www.javabeat.net/wp-content/plugins/digg-digg//js/diggdigg-floating-bar.js?ver=5.3.0"></script><div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2013/04/photo-viewer-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Top 10 JavaScript Tips for your site</title>
		<link>http://www.javabeat.net/2011/02/top-10-javascript-tips-for-your-site/</link>
		<comments>http://www.javabeat.net/2011/02/top-10-javascript-tips-for-your-site/#comments</comments>
		<pubDate>Thu, 24 Feb 2011 04:50:48 +0000</pubDate>
		<dc:creator>JavaBeat</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=523</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Introduction A good looking site is always more preferable than a bland looking site with a boring layout. To jazz up any site, a developer uses JavaScript. It is a popular programming language that used in creating a website with interactive content &#38; elements. The script is browser based and runs independently from page to [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h2>Introduction</h2>
<p>A good looking site is always more preferable than a bland looking site with a boring layout. To jazz up any site, a developer uses <b>JavaScript</b>. It is a popular programming language that used in <a HREF="http://www.createhostwebsites.com/" TARGET="_BLANK">creating a website</a> with interactive content &amp; elements. The script is browser based and runs independently from page to page. Integrating java codes into a site is easy to create stunning looking websites. Here, you can find 10 scripts that are highly recommended for any website developer or designers.</p>
<h2>1. No-Right Click Java Script</h2>
<p>Right clicking is second nature to most web users. To avoid them from right clicking on your site, this <b>javascript</b> code can be used. It is mostly to avoid duplication of the information that is used on the site. Those who view the site, due to this code won’t be able to carry out even the normal functions like ‘copy &amp; paste’, thus avoiding any possible data theft.</p>
<h2>2. Counters</h2>
<p>Google analytics is the best source to keep a track of visitors visiting the site. But, every time one wants to view the stats for their sites, they are required to log into their account, which is quite tedious. To make it easier in viewing the number of visitors a site can be installed with a ‘counter’ <b>javascript</b>. Having this <b>javascript</b> installed can enable the site to display the count for visitors frequenting the website. It is mostly useful for making constructive changes to render the site more traffic friendly.</p>
<h2>3. World Time</h2>
<p>Internet isn’t restricted to any particular time zone and that any website is accessible from anywhere in the world, it’s a good idea to have a world time clock displayed on the site. It is mostly to aid the visitors, and does little to attract traffic. This <b>javascript</b> is purely a visual element.</p>
<h2>4. Animations</h2>
<p>Those websites with fun animations are really great to look. Some sites are solely capable of attracting traffic on the basis of their use of interesting visual elements. So with the use of <b>javascript</b> to create fun &amp; interesting apps or graphic for the site will surely boost the number of visitors on the site. What kind of animation to be used, solely depends on the developer and his preference.</p>
<h2>5. Image Shuffle</h2>
<p>Site that has lots and lots of images, it can get pretty confusing for the user to go through each them, and find the appropriate one. Using a script to constantly display a shuffling image is much better than the traditional thumbnail view and facilitates the use to use the site in much better way. The shuffling images also add an interesting effect to the entire layout of the site. This <b>javascript</b> is useful and also is very much helpful in increasing the ‘visually appealing’ quotient of a site.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<h2>6. Special Navigation</h2>
<p>There is nothing more appealing on a site than a dedicated and easy to use navigation list or button. These are mostly drop down list, which contains categories or dates that can be used for browsing the content of the website. It is easy to install using <b>javascript</b> coding, and certain elements can be tweaked to render the navigation button/menu with some extra useful capabilities.</p>
<h2>7. Colorful Scroll Bars</h2>
<p>Making changes to color is one of the most common used in java scripting. It is done to add a personal touch to the entire layout using the color of choice. On most sites the scroll bar is usually grey. But, it can be changed to whatever color the user wishes to have, using java script. It adds a certain visual touch that makes the site appear attractive.</p>
<h2>8. Bookmarks</h2>
<p>Adding a site to your bookmark list is not a new thing. To extent the capabilities, one can integrate a better bookmarking tool, which can be used by the users who view the site. It will help them remember the page, without doing much search for the site the next time they want to visit the site.</p>
<h2>9. Music Players</h2>
<p>Create a versatile music player with the use of java script coding, and integrate it into the site so that people who like to listen to music, while browsing can find it useful.  Any media player is interesting to look at and adding a media player to the site will jazz up the attractive factor that much more.</p>
<h2>10. Password Protection</h2>
<p>Password protecting a page isn’t recommended for most. But, for those few who do want to make their pages visible to only few, they can password protect it using a java code. With such pages, a user visiting the site won’t be able to view it, unless the person retains a proper password. Password protecting a page is huge turn off and should be used only when absolutely sure.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2011/02/top-10-javascript-tips-for-your-site/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using YUI to attach JavaScript event listeners</title>
		<link>http://www.javabeat.net/2011/01/using-yui-to-attach-javascript-event-listeners/</link>
		<comments>http://www.javabeat.net/2011/01/using-yui-to-attach-javascript-event-listeners/#comments</comments>
		<pubDate>Sat, 29 Jan 2011 15:26:39 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=1472</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Yahoo User Interface 2.X CookbookWelcome to Yahoo User Interface 2.x Cookbook. The Yahoo! User Interface (YUI) Library is a set of utilities and controls, written in JavaScript, for building richly interactive web applications using techniques such as DOM scripting, DHTML, and AJAX. Although you can create stylish Internet applications by modifying its default components, even [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><center><strong>Yahoo User Interface 2.X Cookbook</strong></center>Welcome to Yahoo User Interface 2.x Cookbook. The Yahoo! User Interface (<strong>YUI</strong>) Library is a set of utilities and controls, written in JavaScript, for building richly interactive web applications using techniques such as <strong>DOM</strong> scripting, DHTML, and <strong>AJAX</strong>. Although you can create stylish Internet applications by modifying its default components, even advanced users find it challenging to create impressive feature-rich Internet applications using <strong>YUI</strong>.</p>
<p>This book will help you learn how to use <strong>YUI</strong> 2.x to build richer, more interactive web applications that impress clients and wow your friends. It starts by explaining the core features of <strong>YUI</strong> 2.x, the utilities that the rest of the library depends on and that will make your life easier. It then explains how to build UI components and make <strong>AJAX</strong> requests using the <strong>YUI</strong> framework. Each recipe will cover the most common ways to use a component and how to configure it, and then explain any other features that may be available. We wrap things up by looking at some of the recent beta components and explain how to use them, and how they may be useful on your web application.</p>
<p><strong>What This Book Covers</strong></p>
<p>Chapter 1: Using <strong>YUI</strong> 2.x, teaches various techniques for including <strong>YUI</strong> into your project, and how to use the Get, Cookie, and <strong>JSON</strong> utilities.</p>
<p>Chapter 2: Using <strong>DOM</strong> and Selector Components, teaches how to use the <strong>DOM</strong> and Selector components to fetch and manipulate <strong>DOM</strong> elements.</p>
<p>Chapter 3: Using Event Component, teaches how to attach events to <strong>DOM</strong> elements and how to use the powerful custom event system to create your own events.</p>
<p>Chapter 4: Using Connection Component, teaches how to make <strong>AJAX </strong> requests with <strong>YUI</strong> and subscribe to related events.</p>
<p>Chapter 5: Using DataSource Component, teaches how to abstract away sources of data with a powerful and easy to use interface.</p>
<p>Chapter 6: Using Logger and <strong>YUI</strong> Test Components, teaches how to use <strong>YUI</strong> to log <strong>JavaScript</strong> and then how to test your <strong>JavaScript</strong> applications.</p>
<p>Chapter 7: Using Element and Button Components, teaches how to leverage Element to simplify working with <strong>DOM</strong> elements, and Button to simplify working with Button elements.</p>
<p>Chapter 8: Using Menu Component, teaches how to create and manage Menu objects.</p>
<p>Chapter 9: Using Animation Component, teaches how to use <strong>YUI</strong> to animate <strong>DOM</strong> elements.</p>
<p>Chapter 10: Using Drag and Drop Component, teaches how to use the Drag and Drop utility.</p>
<p>Chapter 11: Using Container Component, teaches all about the container stack and the various widgets that make use of it.</p>
<p>Chapter 12: Using DataTable Component, teaches how to use DataTable to build more useful and interactable tables.</p>
<p>Chapter 13: Using TreeView Component, teaches how to use TreeView to organize hierarchical data.</p>
<p>Chapter 14: Other Useful Components, teaches the basics about some of the other well established widgets, such as Autocomplete and Slider.</p>
<p>Chapter 15: Some Interesting Beta Components, teaches the basics about some of the latest widgets, such as Storage and Charts.</p>
<h2 style="text-align: center;"><span style="text-decoration: underline;"><span style="color: #000080; text-decoration: underline;">Using Event Component</span></span></h2>
<p>In this chapter, we will cover:</p>
<ul>
<li>Using <strong>YUI</strong> to attach <strong>JavaScript</strong> event listeners</li>
<li>Event normalization functions</li>
<li>Removing event listeners</li>
<li>Listening for key events</li>
<li>Using special <strong>YUI</strong>-only events</li>
<li>Using <strong>YUI</strong> helper functions</li>
<li>Using custom events</li>
<li>The simple way to add custom events to classes</li>
</ul>
<p><span style="font-size: 13px;">In this chapter, you will learn how to use </span><strong style="font-size: 13px;">YUI</strong><span style="font-size: 13px;"> to handle </span><strong style="font-size: 13px;">JavaScript</strong><span style="font-size: 13px;"> events, what special events </span><strong style="font-size: 13px;">YUI</strong><span style="font-size: 13px;"> has to improve the functionality of some </span><strong style="font-size: 13px;">JavaScript</strong><span style="font-size: 13px;"> events, and how to write custom events for your own application.</span></p>
<h2>Using <strong>YUI</strong> to attach <strong>JavaScript</strong> event listeners</h2>
<p>When attaching events in <strong>JavaScript</strong> most browsers use the addEventListener function, but the developers of IE use a function called attachEvent. Legacy browsers do not support either function, but instead require developers to attach functions directly to element objects using the &#8216;on&#8217; + eventName property (for example myElement.onclick=function(){&#8230;}).</p>
<p>Additionally, the execution context of event callback functions varies depending on how the event listener is attached. The Event component normalizes all the cross-browser issues, fixes the execution context of the callback function, and provides additional event improvements. This recipe will show how to attach <strong>JavaScript</strong> event listeners, using <strong>YUI</strong>.</p>
<h2>How to do it&#8230;</h2>
<p>Attach a click event to an element:</p>
<pre class="brush: java; title: ; notranslate">var myElement = YAHOO.util.Dom.get('myElementId');
	var fnCallback = function(e) {
		alert(&quot;myElementId was clicked&quot;);
	};
	YAHOO.util.Event.addListener(myElement, 'click', fnCallback);</pre>
<p>Attach a click event to an element by its ID:</p>
<pre class="brush: java; title: ; notranslate">var fnCallback = function(e) {
		alert(&quot;myElementId was clicked&quot;);
	};
	YAHOO.util.Event.addListener('myElementId','click',fnCallback)</pre>
<p>Attach a click event to several elements at once:</p>
<pre class="brush: java; title: ; notranslate">var ids = [&quot;myElementId1&quot;, &quot;myElementId2&quot;, &quot;myElementId3&quot;];
	var fnCallback = function(e) {
		var targ = YAHOO.util.Event.getTarget(e);
		alert(targ.id + &quot; was clicked&quot;);
	};
	YAHOO.util.Event.addListener(ids, 'click', fnCallback);</pre>
<p>When attaching event listeners, you can provide an object as the optional fourth argument, to be passed through as the second argument to the callback function:</p>
<pre class="brush: java; title: ; notranslate">var myElem = YAHOO.util.Dom.get('myElementId');
	var fnCallback = function(e, obj) {
		alert(obj);
	};
	var obj = &quot;I was passed through.&quot;;
	YAHOO.util.Event.addListener(myElem,'click',fnCallback,obj);</pre>
<p>When attaching event listeners, you can change the execution context of the callback function to the fourth argument, by passing true as the optional fi fth argument:</p>
<pre class="brush: java; title: ; notranslate">var myElement = YAHOO.util.Dom.get('myElementId');
	var fnCallback = function(e) {
		alert('My execution context was changed.');
	};
	var ctx = {
		/* some object to be the execution context of callback */
	};
	YAHOO.util.Event.addListener(
		myElement, 'click', fnCallback, ctx, true);</pre>
<h2>How it works&#8230;</h2>
<p>The addListener function wraps the native event handling functions, normalizing the crossbrowser differences. When attaching events, <strong>YUI</strong> calls the correct browser specifi c function, or defaults to legacy event handlers. Before executing the callback function, the Event component must (in some browsers) fi nd the event object and adjust the execution context of the callback function. The callback function is normalized by wrapping it in a closure function that executes when the browser event fi res, thereby allowing <strong><a href="http://www.javabeat.net/books/yui/1/">YUI</a></strong> to correct the event, before actually executing the callback function.</p>
<p>In legacy browsers, which can only have one callback function per event type, <strong>YUI</strong> attaches a callback function that iterates through the listeners attached by the addListener function.</p>
<h2>There&#8217;s more&#8230;</h2>
<p>The addListener function returns true if the event listener is attached successfully and false otherwise.</p>
<p>If the element to listen on is not available when the addListener function is called, the function will poll the <strong>DOM</strong> and wait to attach the listener when the element becomes available.</p>
<p>Additionally, the Event component also keeps a list of all events that it has attached. This list is maintained to simplify removing events listeners, and so that all event listeners can be removed when the end-user leaves the page.</p>
<p>Find all events attached to an element:</p>
<pre class="brush: java; title: ; notranslate">var listeners = YAHOO.util.Event.getListeners('myElementId');
	for (var i=0,j=listeners.length; i&lt;j; i+=1) {
		var listener = listeners[i];
		alert(listener.type); // event type
		alert(listener.fn); // callback function
		alert(listener.obj); // second argument of callback
		alert(listener.adjust); // execution context
	}</pre>
<p>Find all events of a certain type attached to an element:</p>
<pre class="brush: java; title: ; notranslate">// only click listeners
	var listeners =
		YAHOO.util.Event.getListeners('myElementId', 'click');

		The garbage collector in JavaScript does not always do a good job cleaning up
		event handlers. When removing nodes from the DOM, remember to remove
		events you may have added as well.</pre>
<p>The garbage collector in <strong>JavaScript</strong> does not always do a good job cleaning up event handlers. When removing nodes from the <strong>DOM</strong>, remember to remove events you may have added as well.</p>
<h3>More on YAHOO.util.Event.addListener</h3>
<p>The addListener function has been aliased by the shorter on function:</p>
<pre class="brush: java; title: ; notranslate">var myElement = YAHOO.util.Dom.get('myElementId');
	var fnCallback = function(e) {
		alert(&quot;myElementId was clicked&quot;);
	};
	YAHOO.util.Event.on(myElement, 'click', fnCallback);</pre>
<p>By passing an object in as the optional fifth argument of addListener, instead of a Boolean, you can change the execution context of the callback to that object, while still passing in an another object as the optional fourth argument:</p>
<pre class="brush: java; title: ; notranslate">var myElement = YAHOO.util.Dom.get('myElementId');
	var fnCallback = function(e, obj) {
		// this executes in the context of 'ctx'
		alert(obj);
	};
	var obj = &quot;I was passed through.&quot;;
	var ctx = {
		/* some object to be the execution context of callback */
	};
	YAHOO.util.Event.addListener(
		myElement,'click',fnCallback,obj, ctx);</pre>
<p>Lastly, there is an optional Boolean value that can be provided as the sixth argument of addListener, which causes the callback to execute in the event capture phase, instead of the event bubbling phase. You probably won&#8217;t ever need to set this value to true, but if you want to learn more about <strong>JavaScript</strong> event phases see:</p>
<pre class="brush: java; title: ; notranslate">http://www.quirksmode.org/js/events_order.html</pre>
<h2>See also</h2>
<p>Refer to Removing event listeners, to learn about how to remove event callbacks when they are not longer needed.</p>
<h1>Event normalization functions</h1>
<p>The event object, provided as the first argument of the callback function, contains a variety of values that you may need to use (such as the target element, character code, etc.). <strong>YUI </strong>provides a collection of static functions that normalizes the cross-browser variations of these values. Before trying to use these properties, you should read this recipe, as it walks you through each of those functions.</p>
<h2>How to do it&#8230;</h2>
<p>Fetch the normalized target element of an event:</p>
<pre class="brush: java; title: ; notranslate">var fnCallback = function(e) {
		var targetElement = YAHOO.util.Event.getTarget(e);
		alert(targetElement.id);
	};
	YAHOO.util.Event.on('myElementId', 'click', fnCallback);</pre>
<p>Fetch the character code of a key event (also known as the key code):</p>
<pre class="brush: java; title: ; notranslate">var fnCallback = function(e) {
		var charCode = YAHOO.util.Event.getCharCode(e);
		alert(charCode);
	};
	YAHOO.util.Event.on('myElementId', 'keypress', fnCallback);</pre>
<p>Fetch the x and y coordinates of a mouse event:</p>
<pre class="brush: java; title: ; notranslate">var fnCallback = function(e) {
		var x = YAHOO.util.Event.getPageX(e);
		var y = YAHOO.util.Event.getPageY(e);
		alert(&quot;x-position=&quot; + x + &quot; and x-position= &quot; + y);
	};
	YAHOO.util.Event.on('myElementId', 'click', fnCallback);</pre>
<p>Fetch both the x and y coordinates of a mouse event, using:</p>
<pre class="brush: java; title: ; notranslate">var fnCallback = function(e) {
		var point = YAHOO.util.Event.getXY(e);
		alert(&quot;x-position=&quot;+point[0]+&quot; and x-position= &quot;+point[1]);
	};
	YAHOO.util.Event.on('myElementId', 'click', fnCallback);</pre>
<p>Fetch the normalized related target element of an event:</p>
<pre class="brush: java; title: ; notranslate">var fnCallback = function(e) {
		var targetElement = YAHOO.util.Event.getRelatedTarget(e);
		alert(targetElement.id);
	};
	YAHOO.util.Event.on('myElementId', 'click', fnCallback);</pre>
<p>Fetch the normalized time of an event:</p>
<pre class="brush: java; title: ; notranslate">var fnCallback = function(e) {
		var time = YAHOO.util.Event.getTime(e);
		alert(time);
	};
	YAHOO.util.Event.on('myElementId', 'click', fnCallback);</pre>
<p>Stop the default behavior, propagation (bubbling) of an event, or both:</p>
<pre class="brush: java; title: ; notranslate">var fnCallback = function(e) {
		// prevents the event from bubbling up to ancestors
		YAHOO.util.Event.stopPropagation(e);
		// prevents the event's default
		YAHOO.util.Event.preventDefault(e);
		// prevents the event's default behavior and bubbling
		YAHOO.util.Event.stopEvent(e);
	};
	YAHOO.util.Event.on('myElementId', 'click', fnCallback);</pre>
<h2>How it works&#8230;</h2>
<p>All of these functions test to see if a value exists on the event for each cross-browser variation of a property. The functions then normalize those values and return them. The stopPropogation and preventDefault functions actually modify the equivalent cross-browser property of the event, and delegate the behavior to the browsers.</p>
<h2>See also</h2>
<p>Refer to Using <strong>YUI</strong> helper functions, for information on event delegation, which can be used to improve the performance of events.</p>
<h2>Removing event listeners</h2>
<p>As with attaching listeners, there are two browser variations for removing events and legacy browser considerations as well. Additionally, when using the native event removal functions, you must pass in exactly the same arguments as you passed to the native add event functions. <strong>YUI</strong> not only handles the cross-browser variations, but ensures that you pass the correct arguments when removing a function. This recipe shows several ways to remove event listeners from elements.</p>
<h2>How to do it&#8230;</h2>
<p>Remove a callback function directly, by passing in the exact same arguments you used when calling addListener:</p>
<pre class="brush: java; title: ; notranslate">YAHOO.util.Event.removeListener('myElementId', 'click',
		fnCallback);</pre>
<p>Removing all events of a specific type does not require the arguments from addListener:</p>
<pre class="brush: java; title: ; notranslate">// removes all 'click' type events from 'myElementId'
	YAHOO.util.Event.removeListener('myElementId', 'click');</pre>
<p>Remove all listeners from an element:</p>
<pre class="brush: java; title: ; notranslate">YAHOO.util.Event.purgeElement('myElementId');</pre>
<p>Remove all listeners from an element and its descendant elements recursively:</p>
<pre class="brush: java; title: ; notranslate">YAHOO.util.Event.purgeElement('myElementId', true);</pre>
<p>Remove all events of a specific type from an element and its descendant elements recursively:</p>
<pre class="brush: java; title: ; notranslate">
// removes all 'click' type events
	YAHOO.util.Event.purgeElement('myElementId', true, 'click');
</pre>
<h2>How it works&#8230;</h2>
<p>In most cases <strong>YUI</strong> calls the native browser remove listener function, with the proper arguments from the internal array of listeners, and removes the listeners from its internal array. In legacy browsers, <strong>YUI</strong> simply deletes the function that was added to the event.</p>
<h2>There&#8217;s more&#8230;</h2>
<p>Like the addListener function, the removeListener functions can accept either an element object or the id attribute of an element as its fi rst parameter. If the element cannot be found, <strong>YUI</strong> fails silently.</p>
<p>To prevent memory leaks and improve site performance, <strong>YUI</strong> attaches an unload event listener, which removes all event listeners when the page unloads. When removing nodes from the <strong>DOM</strong>, you should call purgeElement on any element that might (or whose descendant elements might) have events attached to them.</p>
<h2>Listening for key events</h2>
<p>The native browser support for key events is identical to other events, except in addition to the other properties, the character code is attached to the event object. There are several browser variations to where the character code is stored and some value discrepancies. <strong>YUI</strong> handles these cross-browser issues, as well as adding the ability to test for key combinations (such as &#8216;ctrl&#8217; plus another key), and a simplifi ed interface. This recipe explains how to listen for key events, and how to leverage the more powerful <strong>YUI</strong> key management functions.</p>
<h2>How to do it&#8230;</h2>
<p>Listen for the keypress event and fi nd the character code:</p>
<pre class="brush: java; title: ; notranslate">var fnCallback = function(e) {
		var charCode = YAHOO.util.Event.getCharCode(e);
		alert('Key pressed with character code ' + charCode);
	};
	YAHOO.util.Event.on('myElementId', 'keypress', fnCallback);</pre>
<p>The event callback has some properties which are true when the Alt, Control, or Shift keys are pressed along with the triggering key:</p>
<pre class="brush: java; title: ; notranslate">var fnCallback = function(e) {
		if (e.altKey) {
			alert(&quot;alt key was pressed as well&quot;);
		}
		if (e.ctrlKey) {
			alert(&quot;control key was pressed as well&quot;);
		}
		if (e.shiftKey) {
			alert(&quot;shift key was pressed as well&quot;);
		}
	};
	YAHOO.util.Event.on('myElementId', 'keypress', fnCallback);</pre>
<p>Use the KeyListener function to effortlessly attach key events:</p>
<pre class="brush: java; title: ; notranslate">var fnCallback = function(e) {
		alert(&quot;The enter key was pressed&quot;);
	};
	var keyObj = {keys:13};
	var keyHandle =
		new YAHOO.util.KeyListener('myElemId', keyObj, fnCallback);
		keyHandle.enable();</pre>
<p>Use the KeyListener function to listen for several key events when Ctrl is also pressed:</p>
<pre class="brush: java; title: ; notranslate">var fnCallback = function(e) {
		alert(&quot;Up, Right, Down, or Left and Control was pressed&quot;);
	};
	var keyObj = {
		alt: false,
		ctrl: true,
		shift: false,
		keys: [37,38,39,40]
	};
	var keyHandle =
		new YAHOO.util.KeyListener('myElemId', keyObj, fnCallback);
	keyHandle.enable();</pre>
<p>The KeyListener function returns an object with two functions, enable and disabled, which allow you to turn the event listener on and off:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">// turn off the key listener
	keyHandle.disable();
	// turn on the key listener
	keyHandle.enable();</pre>
<h2>How it works&#8230;</h2>
<p>When subscribing to any key event directly, <strong>YUI</strong> behaves as it does with other events, wrapping the native event and handling-cross browser variations. The getCharCode function checks the event object for the browser variations of character code, and normalizes the value.</p>
<p>The KeyListener function wraps a keydown event with an instantiatable object that checks the character codes before executing the callback. The disable and enable functions of the returned object respectively call removeListener and addListener for you. You must call the enable function before the instantiated KeyListener to work.</p>
<h2>There&#8217;s more&#8230;</h2>
<p>The second argument of the KeyListener function is called the keyData object, and requires the keys property, but the Boolean values alt, ctrl, and shift are optional. The keys property can either be a single or an array of integer character codes.</p>
<p>By default the KeyListener function listens for the keydown event, but you can also specify the keyup event by passing it as a fourth optional argument:</p>
<pre class="brush: java; title: ; notranslate">var fnCallback = function(e) {
		alert(&quot;The escape key was keyed up&quot;);
	};
	var keyObj = {keys:27};
	var KeyListener = YAHOO.util.KeyListener;
	var keyHandle =
		new KeyListener('myElemId', keyObj, fnCallback, 'keyup');
	keyHandle.enable();</pre>
<p>Also, common key codes are available for you on a static object:</p>
<pre class="brush: java; title: ; notranslate">YAHOO.util.KeyListener.KEY = {
		ALT : 18,
		BACK_SPACE : 8,
		CAPS_LOCK : 20,
		CONTROL : 17,
		DELETE : 46,
		DOWN : 40,
		END : 35,
		ENTER : 13,
		ESCAPE : 27,
		HOME : 36,
		LEFT : 37,
		META : 224,
		NUM_LOCK : 144,
		PAGE_DOWN : 34,
		PAGE_UP : 33,
		PAUSE : 19,
		PRINTSCREEN : 44,
		RIGHT : 39,
		SCROLL_LOCK : 145,
		SHIFT : 16,
		SPACE : 32,
		TAB : 9,
		UP : 38
	};</pre>
<h2>Using special YUI only events</h2>
<p>The Event component has two special events to bubble the focus and blur events, and two events that emulate IE&#8217;s mouseenter and mouseleave events. This recipe explains how to use each of these events.</p>
<h2>Getting ready</h2>
<p>Use the following <strong>DOM</strong> for the examples in this recipe:</p>
<pre class="brush: java; title: ; notranslate">&lt;div id=&quot;myElementId&quot;&gt;
		&lt;h3 id=&quot;myHeaderId&quot;&gt;Example Title&lt;/h3&gt;
		&lt;input name=&quot;myTextInput1&quot; type=&quot;text'/&gt;
		&lt;input name=&quot;myTextInput2&quot; type=&quot;text'/&gt;
		&lt;input name=&quot;myTextInput3&quot; type=&quot;text'/&gt;
	&lt;/div&gt;</pre>
<p>You will need to include the event-mouseenter optional component for the mouse events in this recipe:</p>
<pre class="brush: java; title: ; notranslate">&lt;script src=&quot;pathToBuild/event-mouseenter/event-mouseenter-min.js&quot;
		type=&quot;text/javascript&quot;&gt;&lt;/script&gt;</pre>
<h2>How to do it&#8230;</h2>
<p>Use the special focusin event to handle bubbling focus events:</p>
<pre class="brush: java; title: ; notranslate">// the focus of all 3 inputs can be handled by one callback
	YAHOO.util.Event.on(&quot;myElementId&quot;, &quot;focusin&quot;, function(e) {
		var targ = YAHOO.util.Event.getTarget(e);
		alert(&quot;focused on target: &quot; + targ.name);
	});</pre>
<p>Use the special focusout event to handle bubbling blur events:</p>
<pre class="brush: java; title: ; notranslate">// the blur of all 3 inputs can be handled by one callback
	YAHOO.util.Event.on(&quot;myElementId&quot;, &quot;focusout&quot;, function(e) {
		var targ = YAHOO.util.Event.getTarget(e);
		alert(&quot;blurred on target: &quot; + targ.name);
	});</pre>
<p>Use the mouseenter event to fi re an event once when the mouse first enters an element:</p>
<pre class="brush: java; title: ; notranslate">// this callback fire once when the mouse enters the p tag
	YAHOO.util.Event.on('myHeaderId', 'mouseenter', function(e){
		alert(&quot;Mouse entered: &quot; + this.id);
	});</pre>
<p>Use the mouseleave event to fi re an event once when the mouse first leaves an element:</p>
<pre class="brush: java; title: ; notranslate">// this callback fire once when the mouse enters the p tag
	YAHOO.util.Event.on('myHeaderId', 'mouseleave', function(e){
		YAHOO.log(&quot;Mouse left: &quot; + this.id);
	});</pre>
<h2>How it works&#8230;</h2>
<p>The focusin and focusout are special-cased events that leverage the capture phase of <strong>JavaScript</strong> events to emulate bubbling of blur and focus events.</p>
<p>The mouseenter and mouseleave events use IE&#8217;s native event of the same name, but in other browsers <strong>YUI</strong> adds listeners to the mouseover and mouseout events of an element to emulate the behavior. <strong>YUI</strong> removes or re-attaches these events as necessary, to minimize the number of event subscribers.</p>
<h2>Using YUI helper event functions</h2>
<p><strong>YUI</strong> events have four useful helpers functions: delegate, onAvailable, onContentReady, and onDOMReady. These functions augment how developers interact with the <strong>DOM</strong>. This recipe explains how they work.</p>
<h2>Getting ready</h2>
<p>To use the delegate function in this recipe, you will need to include the event-delegate and Selector components. Use the following <strong>DOM</strong> for the examples in this recipe:</p>
<pre class="brush: java; title: ; notranslate">&lt;div id=&quot;myElementId&quot;&gt;
		&lt;ul&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot; id=&quot;link1&quot;&gt;Item Type One&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot; id=&quot;link2&quot;&gt;Item Type Two&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot; id=&quot;link3&quot;&gt;Item Type Three&lt;/a&gt;&lt;/li&gt;
		&lt;/ul&gt;
	&lt;/div&gt;</pre>
<h2>How to do it&#8230;</h2>
<p>Use event delegation to have a single handler for all three anchors:</p>
<pre class="brush: java; title: ; notranslate">YAHOO.util.Event.delegate(&quot;myElementId&quot;, &quot;click&quot;,
	function(e, matchedElement, container) {
		// The matchedElement is the default scope
		alert(&quot;Default scope id: &quot; + this.id);
		alert(&quot;Clicked link id: &quot; + matchedElement.id);
		/* The actual click target, which could be the matched item or a
		descendant of it. */
		alert(&quot;Event target: &quot; + YAHOO.util.Event.getTarget(e));
		// The delegation container is passed as a third argument
		alert(&quot;Delegation container: &quot; + container.id);
	}, &quot;li a&quot;);</pre>
<p>Remove event delegation with the removeDelegate function:</p>
<pre class="brush: java; title: ; notranslate">YAHOO.util.Event.removeDelegate(&quot;myElementId&quot;, &quot;click&quot;,
		fnCallback);</pre>
<p>Use onAvailable to fi re a function as soon as an element is detected in the <strong>DOM</strong>:</p>
<pre class="brush: java; title: ; notranslate">var fnCallback = function(obj) {
		alert('myElementId is now available');
	};
	var obj = {/* optional pass-through object */};
	YAHOO.util.Event.onAvailable('myElementId', fnCallback, obj);</pre>
<p>Use onContentReady to fi re a function as soon as an element and its nextSibling are<br />
detected in the <strong>DOM</strong>:</p>
<pre class="brush: java; title: ; notranslate">var fnCallback = function(obj) {
		// the execution context was changed to obj
		alert('myElementId is now ready');
	};
	var obj = {/* optional pass-through object */};
	YAHOO.util.Event.onContentReady('myElementId', fnCallback,
		obj, true);</pre>
<p>Fire a callback function as soon as the <strong>DOM</strong> has fi nished loading:</p>
<pre class="brush: java; title: ; notranslate">var fnCallback = function(obj) {
		// the execution context was changed to window
		alert('The DOM is now available');
	};
	var obj = {/* optional pass-through object */};
	YAHOO.util.Event.onDOMReady(fnCallback, obj, window);</pre>
<h2>How it works&#8230;</h2>
<p>Event delegation works by attaching one event listener, of the specifi ed type, to the container element (argument one). When the specifi ed event type fi res, anywhere on the container element, the <strong>DOM</strong> path from the event target to the container element is compared against the selector specifi ed as the fourth argument of the delegate function. If the selector matches, then the callback function is executed.</p>
<p>The onAvailable and onContentReady functions poll the DOM until the element is available by document.getElementById or the window load event isfired. The onContentReady function only differs from onAvailable, in that it waits until the nextSibling of the element is also available to ensure that its descendants have completely loaded.</p>
<h2>There&#8217;s more&#8230;</h2>
<p>The onAvailable and onContentReady functions have signatures exactly like the addListener function, except without the event type. You can use both functions after the window load event fi res, and they will poll the <strong>DOM</strong> for up to 10 seconds.</p>
<p>The onDOMReady function also shares a signature with addListener, except without the element and event type. The recipes for these three functions show the variations you could use for the optional fourth and fi fth arguments.</p>
<pre class="brush: java; title: ; notranslate">Attaching fewer events to the DOM improves the performance of your
	site. Use the event delegation function as much as possible to reduce
	the number of event listeners.</pre>
<h2>See also</h2>
<p>Refer to Using <strong>YUI</strong> to attach <strong>JavaScript</strong> event listeners, for more information on the optional arguments for onAvailable and onContentReady.</p>
<h2>Using custom events</h2>
<p><strong>YUI</strong> provides a framework for publishing and fi ring arbitrary events that you create. This simple feature drives much of the framework, and is the basis for most of the more complicated widgets covered in this book. This recipe shows you how to create, subscribe to, and fire custom events.</p>
<h2>How to do it&#8230;</h2>
<p>Create a basic custom event:</p>
<pre class="brush: java; title: ; notranslate">var myEvent =	new YAHOO.util.CustomEvent('myEvent');</pre>
<p>Create a custom event, whose callback has the specifi ed execution context:</p>
<pre class="brush: java; title: ; notranslate">var ctx = {};
	var myEvent = new YAHOO.util.CustomEvent('myEvent', ctx);</pre>
<p>Subscribe to a custom event:</p>
<pre class="brush: java; title: ; notranslate">var myCallback = function(eventName, fireArgs, obj) {
		/* … */
	};
	myEvent.subscribe(myCallback);</pre>
<p>Fire a custom event:</p>
<pre class="brush: java; title: ; notranslate">myEvent.fire();</pre>
<p>Unsubscribe one callback from a custom event:</p>
<pre class="brush: java; title: ; notranslate">// the signature is the same as the subscribe function
	if (myEvent.unsubscribe(myCallback)) {
		alert('callback unsubscribed successfully');
	}</pre>
<p>Unsubscribe all callbacks from a custom event:</p>
<pre class="brush: java; title: ; notranslate">myEvent.unsubscribeAll();</pre>
<h2>How it works&#8230;</h2>
<p>The custom event framework maintains an array of all instantiated custom events, and an object to map the event names to the custom event object. Custom event objects contain a list of subscriber callback functions, logic to handle scope normalization, and logic for passing parameters from its constructor, subscribe, and fire functions to each subscriber function. The unsubscribe function removes the specifi ed function by comparing the provided function against each subscriber function, and unsubscribeAll will truncate the array of subscriber functions.</p>
<h2>There&#8217;s more&#8230;</h2>
<p>When calling the fire function of a custom event (and using the default callback signature), you can pass any number of arguments into the fire function, and they will be passed as an array to the second argument of each subscriber function.</p>
<p>When calling the unsubscribe function you should pass it the same signature as well calling the subscribe function to ensure the removal of the correct subscriber function.</p>
<p>The following subsections explain optional arguments that can be provided for the functions discussed in this recipe:</p>
<h3>Instantiation function arguments</h3>
<p>When instantiating a CustomEvent object, you need to only provide the fi rst argument, which is the event name, but you can provide up to four additional arguments:</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2012/04/1.jpg"><img class="aligncenter size-medium wp-image-1474" title="1" alt="" src="http://www.javabeat.net/wp-content/uploads/2012/04/1-300x128.jpg" width="300" height="128" /></a></p>
<p><center></center>&nbsp;</p>
<pre class="brush: java; title: ; notranslate">var myEvent = YAHOO.util.CustomEvent('myEvent', this, false, YAHOO.
	util.CustomEvent.LIST, false);</pre>
<h3>Subscribe function</h3>
<p>When calling the subscribe function you must pass a required callback function as the first argument, but can also pass up to two additional arguments:</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2012/04/2.jpg"><img class="aligncenter size-medium wp-image-1475" title="2" alt="" src="http://www.javabeat.net/wp-content/uploads/2012/04/2-300x54.jpg" width="300" height="54" /></a></p>
<p><center></center>&nbsp;</p>
<pre class="brush: java; title: ; notranslate">var newContext = { /* … */ };
	var obj = { /* … */ };
	var myCallback = function(type, fireArgs, obj) {
		/* … */
	}
	myEvent.subscribe(myCallback, obj, newContext);</pre>
<h3>Subscriber callback functions</h3>
<p>When the signature is CustomEvent.LIST (the default value) the following arguments will be passed to the subscriber callback functions when the custom event is fi red:</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2012/04/3.jpg"><img class="aligncenter size-medium wp-image-1476" title="3" alt="" src="http://www.javabeat.net/wp-content/uploads/2012/04/3-300x69.jpg" width="300" height="69" /></a></p>
<p><center></center>When the signature is CustomEvent.FLAT the following arguments will be passed:</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2012/04/4.jpg"><img class="aligncenter size-medium wp-image-1477" title="4" alt="" src="http://www.javabeat.net/wp-content/uploads/2012/04/4-300x64.jpg" width="300" height="64" /></a></p>
<h2>See also</h2>
<p>Refer to Apply EventProvider to manage custom events on objects for information on how to more effectively use custom events with objects.</p>
<h1>The simple way to add custom events to classes</h1>
<p>Since custom events drive much of the <strong>YUI</strong> framework, the developers have created the YAHOO.util.EventProvider class to simplify interacting with custom events on classes.<br />
This recipe explains how to apply EventProvider to your classes and leverage its subscription model.</p>
<h2>How to do it&#8230;</h2>
<p>Apply EventProvider to your class:</p>
<pre class="brush: java; title: ; notranslate">var MyClass = function() {/* … */};
	MyClass.prototype = {/* … */};
	YAHOO.lang.augment(MyClass, YAHOO.util.EventProvider);
	var myClassInst = new MyClass();</pre>
<p>Create an event on myClassInst:</p>
<pre class="brush: java; title: ; notranslate">myClassInst.createEvent('myEvent');</pre>
<p>Subscribe to an event on myClassInst:</p>
<pre class="brush: java; title: ; notranslate">var myCallback = function() {/* … */};
	myClassInst.subscribe('myEvent', myCallback);</pre>
<p>Test if an event has been created on myClassInst:</p>
<pre class="brush: java; title: ; notranslate">if (myClassInst .hasEvent('myEvent')) {
		alert('myEvent has been created');
	}</pre>
<p>Fire an event on myClassInst:</p>
<pre class="brush: java; title: ; notranslate">myClassInst.fireEvent('myEvent');</pre>
<p>Unsubscribe a callback from an event on myClassInst:</p>
<pre class="brush: java; title: ; notranslate">myClassInst.unsubscribe('myEvent', myCallback);</pre>
<p>Unsubscribe from all callbacks from an event on myClassInst:</p>
<pre class="brush: java; title: ; notranslate">myClassInst.unsubscribeAll('myEvent');</pre>
<p>Unsubscribe all events on myClassInst:</p>
<pre class="brush: java; title: ; notranslate">myClassInst.unsubscribeAll();</pre>
<h2>How it works&#8230;</h2>
<p>When creating an event using the EventProvider framework, <strong>YUI</strong> prefaces the event name with a unique ID, so that custom event names are unique per object. Thus fi ring a custom event called myEvent on object A, does not execute callbacks subscribing to myEvent on object B. Otherwise, the functions work like their counterparts from the previous recipe, except they require you to specify the event name as the fi rst argument. The only exception to this rule is the fireEvent function , which calls the subscriber functions using the CustomEvent.FLAT argument signature, instead of CustomEvent.LIST.</p>
<h2>There&#8217;s more&#8230;</h2>
<p>The createEvent function will return the CustomEvent object that it creates or a previously existing one with the same name. The createEvent function instantiates the custom event object and hence you have less control over the instantiation arguments. However, you can pass a confi guration object as the second optional argument of createEvent, with the following properties:</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2012/04/5.jpg"><img class="aligncenter size-medium wp-image-1473" title="5" alt="" src="http://www.javabeat.net/wp-content/uploads/2012/04/5-300x120.jpg" width="300" height="120" /></a></p>
<p><center></center>&nbsp;</p>
<pre class="brush: java; title: ; notranslate">Any subscriber functions applied using the subscribe function
	before calling the createEvent function will be lost. Make sure,
	when instantiating classes you made, that you create all events the
	class may use.</pre>
<h2>See also</h2>
<p>Using custom events, for more information on optional arguments that can be passed to the event functions.</p>
<p>The extending <strong>JavaScript</strong> objects, the <strong>YUI</strong> way, for more information on how to create your own extendable <strong>JavaScript</strong> objects.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2011/01/using-yui-to-attach-javascript-event-listeners/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
