SitePoint Sponsor

User Tag List

Results 1 to 13 of 13
  1. #1
    SitePoint Zealot soapergem's Avatar
    Join Date
    Mar 2005
    Location
    Madison, WI
    Posts
    165
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    onKeyPress event / Incompatibilities

    I know a lot of JavaScript, but I am humble enough to recognize that my knowledge of the language is still very incomplete--which is why I'm here asking this question! I have an <input> field that only accepts numerical digits (0 through 9). Of course I have the server-side code stripping out any non-numerical characters, but for convenience, I also use a JavaScript that utilizes an onKeyPress event handler to block any non-numerical characters. It is set up like this:
    <input type="text" name="field" id="field" onkeypress="return(numeralsOnly(event));" />
    ...with the corresponding JavaScript function like this:
    function numeralsOnly(evt)
    {
    evt = (evt) ? evt : event;
    var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
    if (charCode > 31 && (charCode < 48 || charCode > 57))
    {
    return false;
    }
    return true;
    }
    What I would like to do is use a window.onload function that will dynamically assign the onKeyPress handler to this <input>, rather than having it hard-coded in the HTML. I tried this, and it worked in both Internet Explorer and Opera, but not in Firefox. I think this is because the browsers all handle event's differently. Here's what I tried:
    window.onload = function()
    {
    document.getElementById('field').onkeypress = function() { return(numeralsOnly(event); };
    }
    Like I said, this seemed to work fine in IE and Opera, but not in Firefox. Any ideas?
    // useless crap about my relationships, philosophy,
    // theology, music and programming projects:

    my $blog = 'http://gordon-myers.com/';

  2. #2
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi soapergem,

    Code:
    window.onload = function()
    {
      document.getElementById('field').onkeypress = function(e) {
      return(numeralsOnly(e || window.event); };
    }

  3. #3
    Programming Team silver trophybronze trophy
    Mittineague's Avatar
    Join Date
    Jul 2005
    Location
    West Springfield, Massachusetts
    Posts
    17,014
    Mentioned
    187 Post(s)
    Tagged
    2 Thread(s)

    bubble - capture

    I did a little testing the other day to learn a bit about how different browsers handle events.
    HTML Code:
    window.onload = function(){
    var elm = document.getElementById("theButton");
    if(elm.addEventListener)
    {
    	alert("addEventListener");
    }
    else
    {
    	alert("NO addEventListener");
    }
    if(elm.attachEvent)
    {
    	alert("attachEvent");
    }
    else
    {
    	alert("NO attachEvent");
    }
    }
    The results:
    • Firefox - addEventListener ONLY
    • IE - attachEvent ONLY
    • Mozilla - addEventListener ONLY
    • Netscape - addEventListener ONLY
    • Opera - BOTH addEventListener AND attachEvent

  4. #4
    SitePoint Zealot soapergem's Avatar
    Join Date
    Mar 2005
    Location
    Madison, WI
    Posts
    165
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks guys! Your very simple technique worked perfectly, Mike. And Mittineague, I've never really used attachEvent() or addEventListener() before, but I've always kind of wondered...what exactly do they do?
    // useless crap about my relationships, philosophy,
    // theology, music and programming projects:

    my $blog = 'http://gordon-myers.com/';

  5. #5
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Good info, Mittineague!

    EDIT:
    Mike grins at Mittineague and makes a comment about 1 finger typing

  6. #6
    Programming Team silver trophybronze trophy
    Mittineague's Avatar
    Join Date
    Jul 2005
    Location
    West Springfield, Massachusetts
    Posts
    17,014
    Mentioned
    187 Post(s)
    Tagged
    2 Thread(s)

    events

    I've been in the habit of putting events inline (learned back in the "stupid javascript tricks" days). But as I'm learning more, I want to "clean up" my code a bit. You know, that "seperate style from mark-up from script" thing.
    From Mozilla Dev
    * It allows adding more than a single handler for an event. This is particularly useful for DHTML libraries or Mozilla extensions that need to work well even if other libraries/extensions are used.
    * It gives you finer-grained control of the phase when the listener gets activated (capturing vs. bubbling)
    * It works on any DOM element, not just HTML elements.
    I few weeks ago I was changing a GM userscript so it would be compatible with Opera's User js. I needed to change event capture to bubble. eg.
    HTML Code:
    newSpan.addEventListener(
    "mouseover",
    function() {
    this.style.textDecoration = "none";
    },
    false);
    the "false".

  7. #7
    SitePoint Zealot soapergem's Avatar
    Join Date
    Mar 2005
    Location
    Madison, WI
    Posts
    165
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    This is kind of a late reply, sorry, but is there a way then to create a cross-browser compatible attachEvent() / addEventListener() method of assigning this onKeyPress function that has multiple parameters? One of these parameters would be "evt", the reference to the event, but others could be arbitrary. Any way of doing this?
    // useless crap about my relationships, philosophy,
    // theology, music and programming projects:

    my $blog = 'http://gordon-myers.com/';

  8. #8
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    is there a way then to create a cross-browser compatible attachEvent() / addEventListener() method of assigning this onKeyPress function...
    Here's one: xAddEventListener.

    ...that has multiple parameters?
    Even if you use something like xAddEventListener your listener still needs to start something like this:
    Code:
    function onEvent(evt)
    {
      evt = evt || window.evt;
      ...
    }
    or you could use something like xEvent.

    In regards to the listener receiving other arguments, you can use a closure...
    Code:
    function bindEventListener(ele, sEvent, fnListener, bCap, arg1, arg2)
    {
      xAddEventListener(ele, sEvent,
        function() {
          // in this function you have access to arg1, arg2, etc.
        }, bCap
      );
    }
    A new closure is created each time you call bindEventListener so each listener has access to its own arguments.

    For reference, the following is from the Prototype library:
    Code:
    Function.prototype.bind = function() {
      var __method = this, args = $A(arguments), object = args.shift();
      return function() {
        return __method.apply(object, args.concat($A(arguments)));
      }
    }
    
    Function.prototype.bindAsEventListener = function(object) {
      var __method = this;
      return function(event) {
        return __method.call(object, event || window.event);
      }
    }

  9. #9
    SitePoint Zealot soapergem's Avatar
    Join Date
    Mar 2005
    Location
    Madison, WI
    Posts
    165
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks! I think I'm learning a lot. But while you're here, one more question...slightly related... I tried to create an onkeydown listener for a text field that would block any form submits when the user presses ENTER. It seems to work in IE7 and Firefox 2, but it failed in Opera 9 and I don't know why. Maybe you do? (I just have it doing some basic output for now just to see that it's working.)
    HTML Code:
    <html>
    <head>
    <script type="text/javascript">
    function blah(evt)
    {
    	evt = ( evt || window.event );
    	evt.code = ( evt.keyCode || evt.which || 0 );
    	evt.targetNode = ( evt.srcElement || evt.target );
    	
    	document.body.appendChild(document.createTextNode(evt.code + ' ' + evt.targetNode.tagName + ' '));
    	
    	//	cancel enter
    	if ( evt.code == 13 )
    	{
    		if ( evt.preventDefault )
    		{
    			evt.preventDefault();
    			evt.stopPropagation();
    		}
    		else
    		{
    			evt.keyCode = 0;
    			evt.returnValue = false;
    		}
    		return false;
    	}
    	return;
    }
    window.onload = function()
    {
    	var oText = document.getElementById('blah');
    	if ( window.addEventListener )
    	{
    		oText.addEventListener('keydown', blah, false);
    	}
    	else if ( window.attachEvent )
    	{
    		oText.attachEvent('onkeydown', blah);
    	}
    }
    </script>
    </head>
    <body>
    <form>
    <input type="text" id="blah" name="blah" />
    </form>
    </body>
    </html>
    Last edited by soapergem; Dec 11, 2006 at 17:09.
    // useless crap about my relationships, philosophy,
    // theology, music and programming projects:

    my $blog = 'http://gordon-myers.com/';

  10. #10
    SitePoint Zealot soapergem's Avatar
    Join Date
    Mar 2005
    Location
    Madison, WI
    Posts
    165
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Note: also doesn't work in Safari. (Yet it does work in IE7 and FF2.)
    // useless crap about my relationships, philosophy,
    // theology, music and programming projects:

    my $blog = 'http://gordon-myers.com/';

  11. #11
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    'keypress' triggers a submit

  12. #12
    SitePoint Zealot soapergem's Avatar
    Join Date
    Mar 2005
    Location
    Madison, WI
    Posts
    165
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    How do you know so much? Is there some enormous manual on JavaScript/JScript/ECMAScript that you've read?
    // useless crap about my relationships, philosophy,
    // theology, music and programming projects:

    my $blog = 'http://gordon-myers.com/';

  13. #13
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Nah, I've just played around with it alot


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •