Para probar su funcionamiento dispondremos dos controles de tipo text con algún contenido. Fijaremos de color azul su fuente. Al tomar foco el control cambiará a color rojo y al perder el foco volverá a color azul.
<!DOCTYPE html>
<html>
<head>
<title>Problema</title>
<script >
window.addEventListener('load',inicializarEventos,false);
function inicializarEventos()
{
var ob1=document.getElementById('text1');
ob1.addEventListener('focus',tomarFoco,false);
ob1.addEventListener('blur',perderFoco,false);
var ob2=document.getElementById('text2');
ob2.addEventListener('focus',tomarFoco,false);
ob2.addEventListener('blur',perderFoco,false);
}
function tomarFoco(e)
{
e.target.style.color='#f00';
}
function perderFoco(e)
{
e.target.style.color='#00f';
}
</script>
<style>
#text1,#text2 {
color:#00f;
}
</style>
</head>
<body>
<form action="#" method="post">
<input type="text" name="text1" id="text1" value="Hola" size="20">
<br>
<input type="text" name="text2" id="text2" value="Hola" size="20">
</form>
</body>
</html>
El código javascript es:
window.addEventListener('load',inicializarEventos,false);
function inicializarEventos()
{
var ob1=document.getElementById('text1');
ob1.addEventListener('focus',tomarFoco,false);
ob1.addEventListener('blur',perderFoco,false);
var ob2=document.getElementById('text2');
ob2.addEventListener('focus',tomarFoco,false);
ob2.addEventListener('blur',perderFoco,false);
}
function tomarFoco(e)
{
e.target.style.color='#f00';
}
function perderFoco(e)
{
e.target.style.color='#00f';
}
Es importante notar que en la función inicializarEventos a cada control de tipo text le definimos dos eventos a capturar:
var ob1=document.getElementById('text1');
ob1.addEventListener('focus',tomarFoco,false);
ob1.addEventListener('blur',perderFoco,false);
Lo mismo para el text2.
Los algoritmos de tomarFoco y perderFoco son similares.