Mouse Wheel Handling in Prototype/Javascript

Sunday, January 27, 2008

Here’s how to handle mouse wheel events in prototype, code heavily borrowed from other places on the net, but brought together and made unobtrusive:


/* Mouse Wheel */

Object.extend(Event, {
	wheel:function (event){
		var delta = 0;
		if (!event) event = window.event;
		if (event.wheelDelta) {
			delta = event.wheelDelta/120; 
			if (window.opera) delta = -delta;
		} else if (event.detail) { delta = -event.detail/3;	}
		return Math.round(delta); //Safari Round
	}
});

SetupMouseWheel = {
	initialize: function() {
		Event.observe(document, 'dom:loaded', this.setup_mouse_wheel);
	},
	
	setup_mouse_wheel: function() {
		Event.observe($('element'), "mousewheel", function(e) { SetupMouseWheel.handleDiv(e) }, false);
		Event.observe($('element'), "DOMMouseScroll", function(e) { SetupMouseWheel.handleDiv(e) }, false); // Firefox
	},
	
	handleDiv: function(e) {
		direction = Event.wheel(e) < 0 ? leftSeek : rightSeek;
		console.log(direction); //handle scroll 
		console.log(Event.wheel(e));
		direction(); //call leftSeek or rightSeek depending on direction.
	}
};

The problem with this code though, and the reason I haven’t found a productive use for this yet is that the browser always scrolls the viewport when it extends beyond screen dimensions. So you have your scroll handler and the browser’s scrolling viewport playing hanky-panky, and it’s not a good sight to see. For applications which always stays within the browser window though, this is useful code.

Tags:

Comment! | Permalink

Self-labeling text entry INPUT boxes using Prototype JS

Tuesday, January 15, 2008

Like previous code snippets, this one is mostly all code and no explanation.

A brief primer: you’ve often seen self-labeling input boxes, the ones that display a label inside in gray text, and when you click replaces with an empty input element using Javascript. This is a simple class to help you achieve that effect:


SelfLabelingBox = {
	initialize: function(box_id, message) {
		this.setup_behavior(box_id, message);
	},
	
	setup_behavior: function(box_id, message) {
		box_id = $(box_id);
		if(box_id) {
			if(box_id.value == '') {
				box_id.value = message;
				box_id.addClassName('inactive');
			}
			Event.observe(box_id, 'focus', function() {
				if(box_id.value == message) {
					box_id.value = '';
					box_id.removeClassName('inactive');
				}
			});
			Event.observe(box_id, 'blur', function() {
				if(box_id.value == '') {
					box_id.addClassName('inactive');
					box_id.value = message;
				}
			});
		}
	}
};

SetupDefaultInputs = {
	initialize: function() {
		Event.observe(document, 'dom:loaded', this.setup_default_inputs);
	},
	
	setup_default_inputs: function() {
		SelfLabelingBox.initialize('search_text', 'Search');
	}
};

Until next time!

Tags:

Comment! | Permalink

Simple Javascript Validation

Saturday, January 12, 2008

I hunted around for a good Javascript class to use for validation and finally clobbered together this from various sources on the net. This should be extremely useful for anyone doing client-side validation.


Validate = {	
	forMinLength: function(whatYouTyped, length_min) {
		var fieldset = whatYouTyped.parentNode;
		var txt = whatYouTyped.value;
		if (txt.length >= length_min) {
			fieldset.className = "valid";
		} else {
			fieldset.className = "invalid";
		}
	},
	
	forMaxLength: function(whatYouTyped, length_max) {
		var fieldset = whatYouTyped.parentNode;
		var txt = whatYouTyped.value;
		if (txt.length < = length_max) {
			fieldset.className = "valid";
		} else {
			fieldset.className = "invalid";
		}
	},

	forLength: function(whatYouTyped, length) {
		var fieldset = whatYouTyped.parentNode;
		var txt = whatYouTyped.value;
		if (txt.length == length) {
			fieldset.className = "valid";
		} else {
			fieldset.className = "invalid";
		}
	},
	
	asEmail: function(whatYouTyped) {
		var fieldset = whatYouTyped.parentNode;
		var txt = whatYouTyped.value;
		if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(txt)) {
			fieldset.className = "valid";
		} else {
			fieldset.className = "invalid";
		}
	},
	
	asNumber: function(whatYouTyped) {
		var fieldset = whatYouTyped.parentNode;
		var txt = whatYouTyped.value;
		if (/^\d+$/.test(txt)) {
			fieldset.className = "valid";
		} else {
			fieldset.className = "invalid";
		}
	},
	
	asEqualTo: function(whatYouTyped, whatYouMatchWith) {
		var fieldset = whatYouTyped.parentNode;
		var txt = whatYouTyped.value;
		var expect = whatYouMatchWith.value;
		if (txt == expect && txt != "") {
			fieldset.className = "valid";
		} else {
			fieldset.className = "invalid";
		}
	},
	
	asNotEqualTovalue: function(whatYouTyped, whatYouMatchWith) {
		var fieldset = whatYouTyped.parentNode;
		var txt = whatYouTyped.value;
		var expect = whatYouMatchWith;
		if (txt != expect) {
			fieldset.className = "valid";
		} else {
			fieldset.className = "invalid";
		}
	},
	
	withRegex: function(whatYouTyped, regex) {
		var fieldset = whatYouTyped.parentNode;
		txt = whatYouTyped.value;
		if (regex.test(txt)) {
			fieldset.className = "valid";
		} else {
			fieldset.className = "invalid";
		}
	}
	
};

How do you use it? This is how:

HTML:


<form name="signup" id="signup">
<label for="alias">Alias <sup>*</sup></label>
<fieldset>
<input type="text" name="alias" id="alias" value="" />
</fieldset>
<br />
<label for="mobile_no">Mobile Number <sup>*</sup></label>
<fieldset>
<input type="text" name="mobile_no" id="mobile_no" />
</fieldset>
<br />
[..]
</form>

CSS (different images for fieldset.valid and fieldset.invalid):


fieldset.valid {
	background:transparent url(/images/bg-fieldset-valid.gif) no-repeat 194px 0px;
}

fieldset.invalid {
	background:transparent url(/images/bg-fieldset-invalid.gif) no-repeat 194px 0px;
}

And I hate onclick and onkeyup, so here’s some unobtrusive Javascript to tie it all in:


SignupValidation = {
	initialize: function() {
		Event.observe(document, "dom:loaded", this.setup_validation)
	},
	
	setup_validation: function() {
		if($('signup_body')) {
			Event.observe($('alias'), 'keyup', function() { 
				Validate.withRegex($('alias'), /^[A-Za-z]+[A-Za-z0-9]{4,}$/);
			});
			Event.observe($('mobile_no'), 'keyup', function() { 
				Validate.withRegex($('mobile_no'), /^9[0-9]{9,9}$/)
			});
		}
	}
};

SignupValidation.initialize();

That’s it. The idea (for those who can’t bother to grok code) is that a fieldset changes its class from valid to invalid depending on the status of the field, this is then reflected in the styling.

AsktheCSSGuy was of much help.

Tags:

Comments (1) | Permalink

Multiple DB connections in Rails/ActiveRecord

Saturday, January 12, 2008

You might often want to connect to different databases using ActiveRecord. Here’s how you do it:


#DB definitions:

class DatabaseCurrent < ActiveRecord::Base
  self.abstract_class = true
  establish_connection settings['database']
end

class DatabaseOld < ActiveRecord::Base
  self.abstract_class = true
  establish_connection settings['database2']
end

#Model definitions (current):

class Video < DatabaseCurrent
  belongs_to :user
  
  set_table_name :videos
end

class Photo < DatabaseCurrent
  belongs_to :user
  
  set_table_name :photos
end

class User < DatabaseCurrent
  has_many :videos
  has_many :photos
  
  set_table_name :user
end

class Tag < DatabaseCurrent
  set_table_name :tag
end

#Model definitions (old):

class FileDB < DatabaseOld
  set_table_name :file
end

Pretty easy. The only thing to note is that you should set_table_name, otherwise, AR chokes up. Also, often you want to directly play directly with SQL. Unfortunately, ActiveRecord::Base.execute doesn’t work any longer (coz it doesn’t have a connection), but you can do it this way:


DatabaseCurrent.connection.execute("SQL")

That’s the tutorial for the day!

Tags:

Comments (2) | Permalink