Skip navigation

Demo page |  Source files

How to create custom events in javascript using jQuery framework? This post trying to answer this question.

HTML construction: There are four DIVs (tl, tr, bl, br) absolutely positioned at four corners within a master DIV (container) with gray background. Each absolutely positioned DIV contains one empty div with class ‘error’ and one button.

<div id="container">
	<div id="tl">
		<div class="error"></div>
		<input id="top-left" type="button" value="submit"/>
	</div>
	<div id="tr">
		<div class="error"></div>
		<input id="top-right" type="button" value="submit"/>
	</div>
	<div id="bl">
		<div class="error"></div>
		<input id="bottom-left" type="button" value="submit"/>
	</div>
	<div id="br">
		<div class="error"></div>
		<input id="bottom-right" type="button" value="submit"/>
	</div>	
</div>

CSS construction:

#container{width:100%;height:100%;position:fixed;}
#tl, #tr, #bl, #br{width:200px;height:200px;position:absolute;background-color:#eee;}
#tr{top:0;right:0;}
#rl{top:0;left:0;}
#br{bottom:0;right:0;}
#bl{bottom:0;left:0;}

Javascript Construction:

var customEvent = (function(){
	$(function(){
		customEvent.init();
	});
	var errorHandler = function(e){
		var formErrorFlag = true;
		if(formErrorFlag) 
			$(this).trigger('formError');
	}
	var customErrorHandler = function(e){
		$('.error').html('error at '+e.target.id).css('color','Red');
	}
	return {
		init: function(){
			$("input:button").bind('click',errorHandler);
			$("input:button").bind('formError',customErrorHandler);
		}
	};
})();

All buttons binded with click event with errorHandler function which in turn triggers custom event called ‘formEvent’ based on some condition ‘formErrorFlag’. So in other words, ‘formEvent’ is my custom event which is trigger based on a boolean ‘formErrorFlag’.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 150 other followers

%d bloggers like this: