Textbox watermark label with Protoype Javascript library

First we'll outline the desired functionality:

  • The textbox should show the label inside the textarea, possibly in a different colour to when normal text is entered, to highlight that it is just a label.
  • When the textbox gains focus (clicked on / tabbed to) the label should disappear.
  • When the textbox loses focus the label should reappear if (and only if) no other text has been entered.
  • The solution should degrade graceful in the absence of JavaScript

As we want to write good semantic XHTML we'll start with the following code:

<label for="searchbox">Search</label>
<input type="textbox" name="q" id="searchbox" value="" />

So with JavaScript disabled we'll get a standard label outside the textbox. If we want the fall-back behaviour to be hide the label, we can do that with CSS.

Now we'll create our Prototype class:

var WatermarkLabel = Class.create({
	initialize: function(id) {
		this.textbox = $(id);
		this.text = '';
 
		var labels = $$('label[for="' + id + '"]');
		if(labels.length) {
			this.text = labels[0].innerHTML;
			Element.hide(labels[0]);
		}
 
		this.textbox.observe('focus', this.focus.bindAsEventListener(this));
		this.textbox.observe('blur', this.blur.bindAsEventListener(this));
		this.blur();
	},
 
	focus: function(event) {
		if(this.empty)
			this.textbox.value = '';
		this.empty = false;
		this.textbox.removeClassName('empty');
	},
 
	blur: function(event) {
		if(this.textbox.value == '') {
			this.textbox.value = this.text;
			this.textbox.addClassName('empty');
			this.empty = true;
		}
	}
});

To initalise the code we simply use:

new WatermarkLabel('searchbox'); //the textbox's "id"

The constructor (initialize) creates a handle on the textbox (this.textbox). It then finds the first associated label, stores it's value (this.text) and hides it. Finally it sets up the event observers on the textbox (blur and focus) and fires the blur event.

The focus and blur events determine if the textbox is empty and clear/restore the label, and add/remove the "empty" class, so the textbox can be styled differently when the label is being show (usually a lighter text colour for the watermark effect).

Further complications may arise if you have other scripts pointing at your textbox that could change it's value. For this we need to set up another listener, and trigger it whenever we change the textbox value (unfortunately we can't manually trigger the 'change' event). Prototype's custom events let us achieve this nicely.

Add the following observer after the first two:

	this.textbox.observe('value:changed', this.change.bindAsEventListener(this));

and add the following method to the class:

	change: function(event) {
		this.empty = (this.textbox.value == '');
		this.textbox.value == '' ? this.blur(event) : this.focus(event);
	}

then whenever we change the value of the textbox with another piece of code we just have to remember to fire the event using:

	textboxElement.fire('value:changed');

All scripts are Public Domain.

Comments

online viagra buy viagra online buy viagra online generic for viagra

online viagra buy viagra online buy viagra online generic for viagra

buy viagra viagra generic name cheap viagra buying viagra online

buy viagra viagra generic name cheap viagra buying viagra online

Write My Essay For Me - EssayErudite.com

Can You [url=https://essayerudite.com/write-essay-for-me/]Write Essay For Me[/url] ? How many times do students worldwide ask this question without finding an answer?
We'd rather not check the official statistics. At the same time, essays appear to be probably among the most popular academic assignments.
Students from various education establishments need to complete them constantly. If you are among those lucky ones, feel free to contact our customer service department and opt for an essay writing help.

Write Essay For Me

Write My Essay For Me - https://essayerudite.com/write-essay-for-me/

Write My Essay For Me - EssayErudite.com

Can You [url=https://essayerudite.com/write-essay-for-me/]Write Essay For Me[/url] ? How many times do students worldwide ask this question without finding an answer?
We'd rather not check the official statistics. At the same time, essays appear to be probably among the most popular academic assignments.
Students from various education establishments need to complete them constantly. If you are among those lucky ones, feel free to contact our customer service department and opt for an essay writing help.

Write Essay For Me

Write My Essay For Me - https://essayerudite.com/write-essay-for-me/

Как выиграть миллионы долларов в одночасье без особого труда - секреты выигрыша.
Рассчитываем реальный шанс выигрыша джекпота в Российские и Мировые лотереи.
Поднимаем вопрос о добросовестности проведения лотерей, в принципе.

Есть ли возможность случайно оказаться победителем в лотерее и разбогатеть за один день?
В статье на сайте мы рассчитываем, каковы же шансы победить у людей, решивших принять участие в лотереи по всему миру, с учётом различных лотерейных правил.

Но не стоит и забывать, что [url=http://www.agentlotto1.com/]призовые в международных лотереях[/url], где выпадают дополнительные шары, многократно превосходят российские.
В заключение, хочется отметить очень интересный нюанс:
в подавляющем большинстве случаев один купленный билет (с одним игровым полем) не станет выигрышным, в нём не совпадут все цифры.
Участвуя в лотереи с бОльшим количеством игровых полей в билете, Вы тем самым увеличиваете вероятность выигрыша джекпота, второго приза, и более мелких призов.
Однако, не подумайте, что хотя бы на один из участвующих лотерейных билетов не упадёт крупная сумма денег выигрыша, джекпота.
Здесь должен быть описан знаменитый «Парадокс лотереи».
Видимо, в азартных играх всё зависит не только от математических формул, но и от удачи игрока!

Как выиграть миллионы долларов в одночасье без особого труда - секреты выигрыша.
Рассчитываем реальный шанс выигрыша джекпота в Российские и Мировые лотереи.
Поднимаем вопрос о добросовестности проведения лотерей, в принципе.

Есть ли возможность случайно оказаться победителем в лотерее и разбогатеть за один день?
В статье на сайте мы рассчитываем, каковы же шансы победить у людей, решивших принять участие в лотереи по всему миру, с учётом различных лотерейных правил.

Но не стоит и забывать, что [url=http://www.agentlotto1.com/]призовые в международных лотереях[/url], где выпадают дополнительные шары, многократно превосходят российские.
В заключение, хочется отметить очень интересный нюанс:
в подавляющем большинстве случаев один купленный билет (с одним игровым полем) не станет выигрышным, в нём не совпадут все цифры.
Участвуя в лотереи с бОльшим количеством игровых полей в билете, Вы тем самым увеличиваете вероятность выигрыша джекпота, второго приза, и более мелких призов.
Однако, не подумайте, что хотя бы на один из участвующих лотерейных билетов не упадёт крупная сумма денег выигрыша, джекпота.
Здесь должен быть описан знаменитый «Парадокс лотереи».
Видимо, в азартных играх всё зависит не только от математических формул, но и от удачи игрока!

order viagra online generic viagra usa buy viagra professional [url=http://viagravkash.com/]generic viagra[/url]

order viagra online generic viagra usa buy viagra professional [url=http://viagravkash.com/]generic viagra[/url]

brand viagra generic viagra 100mg viagra soft tabs cheap viagra online canadian pharmacy

Привет всем участникам! Класный у вас сайт!
Что скажете по поводу этих новостей?:
http://enewz.ru/news/9500-blok-nato-zamok-iz-peska.html [b] Блок НАТО - замок из песка [/b]
http://enewz.ru/news/6915-lugansk-snova-obstrelyan-iz-gradov.html
http://enewz.ru/news/15587-smi-iz-za-sankciy-kremlya-nemeckie-fermery-te...
Ещё много интересного по теме нашел тут: [b] [/b] http://enewz.ru/

Привет всем участникам! Класный у вас сайт!
Что скажете по поводу этих новостей?:
http://enewz.ru/news/9500-blok-nato-zamok-iz-peska.html [b] Блок НАТО - замок из песка [/b]
http://enewz.ru/news/6915-lugansk-snova-obstrelyan-iz-gradov.html
http://enewz.ru/news/15587-smi-iz-za-sankciy-kremlya-nemeckie-fermery-te...
Ещё много интересного по теме нашел тут: [b] [/b] http://enewz.ru/

Paper Writing Service - EssayErudite.com

We value excellent academic writing and strive to provide outstanding [url=https://essayerudite.com]paper writing services[/url] each and every time you place an order. We write essays, research papers, term papers, course works, reviews, theses and more, so our primary mission is to help you succeed academically.

Don't waste your time and order our paper writing service today!

Best Essay Paper Writing Service -https://essayerudite.com

Paper Writing Service - EssayErudite.com

We value excellent academic writing and strive to provide outstanding [url=https://essayerudite.com]paper writing services[/url] each and every time you place an order. We write essays, research papers, term papers, course works, reviews, theses and more, so our primary mission is to help you succeed academically.

Don't waste your time and order our paper writing service today!

Best Essay Paper Writing Service -https://essayerudite.com

Do My Homework - EssayErudite.com

I can't [url=https://essayerudite.com/do-my-homework/]do my homework[/url] alone - that is not a problem anymore. EssayErudite.com will always be by your side whenever you call for writing help.
EssayErudite represents a pool of native-speaking editors, proofreaders, instructors and writers to handle any writing task by the deadline.

I need assistance to do my homework

Do My Homework - https://essayerudite.com/do-my-homework/

Do My Homework - EssayErudite.com

I can't [url=https://essayerudite.com/do-my-homework/]do my homework[/url] alone - that is not a problem anymore. EssayErudite.com will always be by your side whenever you call for writing help.
EssayErudite represents a pool of native-speaking editors, proofreaders, instructors and writers to handle any writing task by the deadline.

I need assistance to do my homework

Do My Homework - https://essayerudite.com/do-my-homework/

discount viagra best place to buy generic viagra online viagra pills [url=http://viagraoahvfn.com/]when will viagra go generic[/url]

discount viagra best place to buy generic viagra online viagra pills [url=http://viagraoahvfn.com/]when will viagra go generic[/url]

viagra tablets generic for viagra viagra 100mg viagra online usa

viagra tablets generic for viagra viagra 100mg viagra online usa

cialis soft buy cialis online cheap tadalafil 20mg where to buy cialis online

cialis soft buy cialis online cheap tadalafil 20mg where to buy cialis online

discount generic viagra buy viagra online usa online generic viagra when does viagra go generic

discount generic viagra buy viagra online usa online generic viagra when does viagra go generic

cialis coupon cialis online pharmacy cialis online no prescription buy generic cialis online

cialis coupon cialis online pharmacy cialis online no prescription buy generic cialis online

buy viagra now viagra generic name womens viagra generic viagra canada

buy viagra now viagra generic name womens viagra generic viagra canada

Buy cialis cialis pills buycialisky.com
generic for cialis or viagra http://buycialisky.com/
tadalafil reviews http://buycialisky.com/
Cialis online
cheapest cialis pharnacy comparisoncialis cialis cialis genuinerx net viagracan cialis cause pain in ribscialis 20 refilviagra le cialis et le levitraconvincing a doctor to prescibe cialiscialis vs viagra number of erectionsou acheter du cialis pas cher
http://eze-trac.com/__media__/js/netsoltrademark.php?d=buycialisky.com

tadalafil without a doctor's prescription tadalafil generic international cialisonl.com
cialis pills for men http://cialisonl.com/
buy cialis online cheap http://cialisonl.com/
buy cialis online without prescription
how to use cialis ultimate pleasurewat werkt beter cialis of viagracheap overnight cialis softcosto de cialis 5 mgtake cialis with viagratestpaket viagra cialishow fast cialis daily work
http://luckie.co/__media__/js/netsoltrademark.php?d=cialisonl.com

cialis without a doctor's prescription in usa cialis tablets side effects cialisonl.com
cialis 5mg coupon lilly http://cialisonl.com/
tadalafil 20mg tab http://cialisonl.com/
cialis without prescription
cheapest generic cialis soft with overnight deliveryvergelijking kamagra cialiscialis dosage informationinternet apotheke cialisdoes medicare cover viagra or cialisdaily cialis vs viagraachat cialis en suissecanadian pharmacy cialis reviewsside effects viagra cialis
http://eatsmartfreshfoods.com/__media__/js/netsoltrademark.php?d=cialiso...

cialis subscription generic cialis online cialisonl.com
tadalafil 10 mg daily http://cialisonl.com/
cialis 5mg coupon lilly http://cialisonl.com/
cialis without prescriptions
cialis shoulder painbuy cialis online online a hrefcialis super actiaddicted to cialisle viagra est il plus efficace que le cialis
http://maddeeps.com/__media__/js/netsoltrademark.php?d=cialisonl.com

cialis subscription generic cialis online cialisonl.com
tadalafil 10 mg daily http://cialisonl.com/
cialis 5mg coupon lilly http://cialisonl.com/
cialis without prescriptions
cialis shoulder painbuy cialis online online a hrefcialis super actiaddicted to cialisle viagra est il plus efficace que le cialis
http://maddeeps.com/__media__/js/netsoltrademark.php?d=cialisonl.com

buy cialis without prescription cialis 20mg cialisonl.com
tadalafil tablets 60 mg http://cialisonl.com/
cialis prices 5mg http://cialisonl.com/
cialis without a doctor's prescription
cialis distributorscheap cialis generic levitra viagraorder cialis soft 180 tabletscialis retail price in cttaking 2 20 mg cialischeap soft cialis 30 tabletsqual o preco do viagra e do cialiscialis e viagra confrontowhat is more expensive viagra or cialiscialis 5 mg tablets cost
http://northfloridanativewoods.com/__media__/js/netsoltrademark.php?d=ci...

buy cialis online without a prescription cialis generico opinion cialisonl.com
tadalafil generic dosage http://cialisonl.com/
buy cialis cheap http://cialisonl.com/
cialis without a doctor's prescription
cialis performancekosten cialis 5 mgblanda viagra och cialisbuy line cialis soft wherecialis $1.00 20mg no prescriptionqual o mais barato viagra ou cialiscialis dosage recommendationscialis en viagra samen innemen
http://petrikin.com/__media__/js/netsoltrademark.php?d=cialisonl.com

buy cialis online without a prescription cialis generico opinion cialisonl.com
tadalafil generic dosage http://cialisonl.com/
buy cialis cheap http://cialisonl.com/
cialis without a doctor's prescription
cialis performancekosten cialis 5 mgblanda viagra och cialisbuy line cialis soft wherecialis $1.00 20mg no prescriptionqual o mais barato viagra ou cialiscialis dosage recommendationscialis en viagra samen innemen
http://petrikin.com/__media__/js/netsoltrademark.php?d=cialisonl.com

cialis without a doctors prescription venta cialis generico cialisonl.com
tadalafil tablets http://cialisonl.com/
cialis uk suppliers http://cialisonl.com/
tadalafil without a doctor's prescription
cost of cialis and viagracialis for sale south africawhat retirement medical providers cover cialiscialis 10mg gunstig kaufenalternative to viagra cialiscialis pillsonline pharmacy cialis 5mgmouth dissolving generic cialiscl tures sp cialis es
http://digitalmediaonlineinc.com/__media__/js/netsoltrademark.php?d=cial...

tadalafil without a doctor's prescription cialis generic dosage cialisonl.com
generic cialis tadalafil uk http://cialisonl.com/
cialis lowest price coupon http://cialisonl.com/
cialis without doctor prescription
cialis professional 20 mg reviewsis viagra cialis or levitra bettercialis longercut price cialis softmelhor cialis levitra viagra
http://nymtrust.com/__media__/js/netsoltrademark.php?d=cialisonl.com

can you buy viagra in mexico without a prescription cialis uk price cialisonl.com
cialis prices walmart http://cialisonl.com/
cialis prices without insurance http://cialisonl.com/
generic cialis without a doctor prescription
reviews for viagra cialis and levitraon line cialis softprices of viagra and cialisprezzo cialis e viagraviagra cialis espa ol
http://essential2.com/__media__/js/netsoltrademark.php?d=cialisonl.com

can you buy viagra in mexico without a prescription cialis uk price cialisonl.com
cialis prices walmart http://cialisonl.com/
cialis prices without insurance http://cialisonl.com/
generic cialis without a doctor prescription
reviews for viagra cialis and levitraon line cialis softprices of viagra and cialisprezzo cialis e viagraviagra cialis espa ol
http://essential2.com/__media__/js/netsoltrademark.php?d=cialisonl.com

cialis online without prescriptio cialis 5mg cialisonl.com
cialis uk cost http://cialisonl.com/
tadalafil tablets 10mg http://cialisonl.com/
cialis without a doctors prescription
cialis does it workcialis 5 mg cenaprice viagra cialis levitraviagra levitra cialis nosecialis lowest pricesnatural substitute cialis soft
http://louchapter13.com/__media__/js/netsoltrademark.php?d=cialisonl.com

buy cialis without a prescription cialis 5mg generic prices cialisonl.com
tadalafil 20 mg http://cialisonl.com/
cialis 20mg coupon http://cialisonl.com/
cialis purchase online without prescription
cialis long termcialis capsules vs soft tabscialis user reviewviagra taken with cialiswaar kan ik goedkoop cialis kopencialis generico 5 mg precocialis non generic from canadadiscounted cialis 20 mg
http://tryrxgen.com/__media__/js/netsoltrademark.php?d=cialisonl.com

buy cialis without a prescription cialis 5mg generic prices cialisonl.com
tadalafil 20 mg http://cialisonl.com/
cialis 20mg coupon http://cialisonl.com/
cialis purchase online without prescription
cialis long termcialis capsules vs soft tabscialis user reviewviagra taken with cialiswaar kan ik goedkoop cialis kopencialis generico 5 mg precocialis non generic from canadadiscounted cialis 20 mg
http://tryrxgen.com/__media__/js/netsoltrademark.php?d=cialisonl.com

cialis without a doctors prescription purchase cialis cialisonl.com
cialis 5mg price comparison http://cialisonl.com/
cialis 5 mg generic http://cialisonl.com/
cialis without a doctor's prescription
gevaar cialissu cialiscialis retailcialis western opencialis addictionbuy viagra vs cialislegitimate cialis
http://aicent.net/__media__/js/netsoltrademark.php?d=cialisonl.com

cialis without a doctors prescription purchase cialis cialisonl.com
cialis 5mg price comparison http://cialisonl.com/
cialis 5 mg generic http://cialisonl.com/
cialis without a doctor's prescription
gevaar cialissu cialiscialis retailcialis western opencialis addictionbuy viagra vs cialislegitimate cialis
http://aicent.net/__media__/js/netsoltrademark.php?d=cialisonl.com

cialis purchase online without prescription cialis lowest price coupon cialisonl.com
best price generic cialis 20 mg http://cialisonl.com/
buy generic cialis online http://cialisonl.com/
tadalafil without a doctor's prescription
cialis diario 5 mg caixa 28 comprimidos revestidoscialis vs viagra costcialis soft retinitis pigmentosacialis familycomparatif cialis viagra levitraprescription cialis soft withoutmy cialismon roi cialis
http://bks4less.com/__media__/js/netsoltrademark.php?d=cialisonl.com

cialis purchase online without prescription cialis lowest price coupon cialisonl.com
best price generic cialis 20 mg http://cialisonl.com/
buy generic cialis online http://cialisonl.com/
tadalafil without a doctor's prescription
cialis diario 5 mg caixa 28 comprimidos revestidoscialis vs viagra costcialis soft retinitis pigmentosacialis familycomparatif cialis viagra levitraprescription cialis soft withoutmy cialismon roi cialis
http://bks4less.com/__media__/js/netsoltrademark.php?d=cialisonl.com

cialis purchase online without prescription cialis tadalafil 40mg cialisonl.com
cialis prices 5mg http://cialisonl.com/
cialis prices mexico http://cialisonl.com/
cheap cialis without a doctors prescription
pumping with cialischemical name of cialisqual e o melhor viagra cialis levitracialis no rxgeneric cialis 20 mg ukcialis generika kaufen per nachnahme
http://linquest.net/__media__/js/netsoltrademark.php?d=cialisonl.com

cialis daily use without prescription tadalafil generic international cialisonl.com
buy cialis online cheap http://cialisonl.com/
tadalafil 20 mg tablet http://cialisonl.com/
cialis without a doctor's prescription
cialis cialis generico tadalafil compra cialiscialis store onlinewhat is better cialis or viagawhere to buy cialis in ontariois generic cialis the same
http://connectablereality.com/__media__/js/netsoltrademark.php?d=cialiso...

Pages

Add new comment