Blog

horizontal line graphic

Subscribe to Kevin Southworth's Blog  Subscribe to my RSS feed | Categories | Search

Javascript Event Handlers

Wednesday, January 24, 2007 @ 1:51 AM :: 278 Views :: 0 Comments ::
Categories: Software Development

I was looking for a way to attach an event to ALL the input fields on a web page and found this little ditty that lets you attach event handlers to all instances of an element with one call :)

<html>

<head>

<title>title>

<script type="text/javascript" language="Javascript">

function addEvent(obj, evType, fn)

{

    if (obj.addEventListener)

    {

        obj.addEventListener(evType, fn, true);

        return true;

    }

    else if (obj.attachEvent)

    {

        var r = obj.attachEvent("on"+evType, fn);

        return r;

    }

    else

    {

        return false;

    }

}

 

addEvent(window, ''load'', function() {

 var input;

 var inputs = document.getElementsByTagName(''input'');

 for (var i = 0; (input = inputs[i]); i++) {

   addEvent(input, ''blur'', myBlur);

 }

}

);

 

function myBlur()

{

    alert("My Blur");

}

 

script>

head>

<body>

<form name="myform">

header

name: <input type="text" name="fname" /><br>

email: <input type="text" name="femail" /><br>

footer

form>

body>

html>

When the window loads, this code will select all the "input" elements on the page and attach my custom function/event handler "myBlur" to each of them.  Which means that anytime ANY of the input fields loses focus, the myBlur function will be called

Rating
Comments
Currently, there are no comments. Be the first to post one!
Click here to post a comment