<!doctype html>
<html><head>
<script src="file.js"></script></head><body>
<input id="foo" type="text">
</body></html>
Method #1:
in file.js which you reference in the <head>
with a <script>
:
window.onload = function() {
var input = document.getElementById('foo');
input.onfocus = function() { if ( this.value == '' ) { this.value = 'blah';} }
input.onblur = function() { if ( this.value == 'blah') { this.value = ''; } }
}
And ideally you'd want to use an addEvent function which supports dom listeners.
Method #2:
The (arguably) more elegant way would be:
var addEvent = (function() {
function addEventIE(el, ev, fn) {
return el.attachEvent('on' + ev, function(e) {
return fn.call(el, e);
});
}
function addEventW3C(el, ev, fn) {
return el.addEventListener(ev, fn, false);
}
return window.addEventListener ? addEventW3C:addEventIE;
})();
addEvent(window, 'load', function() {
var input = document.getElementById('foo');
addEvent(input, 'blur', function(){});
addEvent(input, 'focus', function(){});
});
Method #3:
You can also avoid the whole onload
and addEvent
nonsense and just put your script before the end body tag if it's a fairly simplistic site.
<script src="file.js"></script>
</body>
file.js:
var input = document.getElementById('foo');
input.onfocus = function() { if ( this.value == '' ) { this.value = 'blah';} }
input.onblur = function() { if ( this.value == 'blah') { this.value = ''; } }