Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 12 of 12
  1. #1
    Regular Coder
    Join Date
    Jul 2002
    Location
    Iran
    Posts
    695
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Adding a new function to onkeypress of an input

    Hi, Let's say I have an input like this:

    Code:
    <input type="text" onkeypress="doSomething();">
    How can I dynamically add a new function to onkeypress without deleting the previous function? I wana do it via a script and the final thing should look like this ( I mean it should behave like this! ):

    Code:
    <input type="text" onkeypress="doSomething(); doSomethingelse();">

  • #2
    Senior Coder
    Join Date
    Jun 2002
    Location
    near Oswestry
    Posts
    4,508
    Thanks
    0
    Thanked 0 Times in 0 Posts
    afaik, if you a bind an event handler to an element you always nullify its existing event handler. But you can read the existing handler with getAttribute and use eval() to call it; something like:
    Code:
    <script type="text/javascript">
    
    
    //this is the original function
    function firstThing()
    {
    	alert("first thing");
    }
    
    
    
    
    //this adds extra handler to element
    window.onload = function()
    {
    	document.getElementById("keybox").onkeypress = function()
    	{
    		//evaluate existing function call
    		eval(document.getElementById("keybox").getAttribute("onkeypress"));
    
    		//do whatever else you want
    		alert("second thing");
    	}
    }
    
    
    </script>
    
    <form>
    <input id="keybox" type="text" onkeypress="firstThing()">
    </form>
    "Why bother with accessibility? ... Because deep down you know that the web is attractive to people who aren't exactly like you." - Joe Clark

  • #3
    Master Coder
    Join Date
    Feb 2003
    Location
    Umeå, Sweden
    Posts
    5,575
    Thanks
    0
    Thanked 83 Times in 74 Posts
    Why not do this:
    Code:
    function extendEvent(oElement,sEvent,fnNew){
        oElement=oElement||window;
        sEvent=/^on/.test(sEvent)?sEvent:'on'+sEvent;
        var
            fnOld=oElement[sEvent]||function(){};
        return (oElement[sEvent]=function(){
            var res=[
                fnOld(),
                fnNew()
            ];
        return (res[0]&&res[1]);
        });
    }
    I just wish you could have done Function.prototype.extend(fnNew) instead, but JavaScript doesn't allow you to overwrite this.

    (This is my 200th post. yay!)
    Last edited by liorean; 04-02-2003 at 11:30 AM.
    liorean <[lio@wg]>
    Articles: RegEx evolt wsabstract , Named Arguments
    Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
    Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards

  • #4
    Regular Coder
    Join Date
    Jul 2002
    Location
    Iran
    Posts
    695
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thank you both, you really helped.

    To be honest dear liorean, since you're much better than me in JS, I can't understand your code! Brothercake's code looks easier and I can understand it, so, I think I'm gonna use it.

    Even though not related to this thread, but I was looking for this functionality because I had one function that had to be called for unknown times for unknown variables in an onkeypress. So, I wanted to add to the number of functions in onkeypress whenever I had to add a new variable dynamically. But now I'm looking at the problem from a different angle! I defined an attribute for my input field that I keep an array in it. This array contains those elements ( variables ) and in each onkeypress I iterate through the array elements ( You were in that post that I asked about my problem with fancy attributes not working in NS7 ). So, my problems is somehow solved, but thank you both for teaching me a new thing.

    bijan
    Last edited by ConfusedOfLife; 04-02-2003 at 08:50 PM.

  • #5
    Master Coder
    Join Date
    Feb 2003
    Location
    Umeå, Sweden
    Posts
    5,575
    Thanks
    0
    Thanked 83 Times in 74 Posts
    Oh, I guess I'm using a few shortcuts instead of more familiar features... If you were a c/c++ programmer, you wouldn't even think about it - they come naturally.
    [list=1][*] Instead of if..else, I use conditional:

    condition?expression if true:expression if false;
    [*] I also use shortcut validation when able:

    first expression||second expression;

    If the first expression evaluates to anything other than undefined, null, false, 0 or an empty string, it returns the result of the first expression. Otherwise, it returns the result of the second expression.


    first expression&amp;&amp;second expression;

    If the first expression evaluates to anything of undefined, null, false, 0 or an empty string, it returns the result of the first expression. Otherwise, it returns the result of the second expression.
    [*] I like to use array and object literals:

    var
    array=[
    first element,
    ...,
    last element
    ];

    var
    object={
    identifier:element,
    ...,
    last identifier:element
    };
    [*] I also use regular expressions frequently. For more info on regular expressions, see my tutorial about them on evolt or javascript kit.[/list=1]
    Last edited by liorean; 04-02-2003 at 09:17 PM.
    liorean <[lio@wg]>
    Articles: RegEx evolt wsabstract , Named Arguments
    Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
    Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards

  • #6
    Senior Coder
    Join Date
    Jun 2002
    Location
    near Oswestry
    Posts
    4,508
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Interesting ... I must admit, I find your code a bit difficult to follow sometimes - I also use object and array literals, ternary statements, and regular expression tests, but I don't like to miss out braces because it makes the flow of logic more difficult to trace, and I don't 'approve' of automatic-type conversion when evaluating statements - scripts execute more quickly if you code to strict.


    ConfusedOfLife - incidentally - that code I posted reads and evaluates whatever keypress function-call is there, which is useful because you don't have to know what it is. But (I guess I should mention) it doesn't work in IE - the first function simply won't be called.

    You can make it work in IE, if you can call the function by name, just by replacing:

    eval(document.getElementById("keybox").getAttribute("onkeypress"));

    with the call to your function:

    firstThing();
    Last edited by brothercake; 04-02-2003 at 10:30 PM.
    "Why bother with accessibility? ... Because deep down you know that the web is attractive to people who aren't exactly like you." - Joe Clark

  • #7
    Master Coder
    Join Date
    Feb 2003
    Location
    Umeå, Sweden
    Posts
    5,575
    Thanks
    0
    Thanked 83 Times in 74 Posts
    Actually, I try to code to mozilla's strict warnings as much as possible - but sometimes I fall back to my older, more load-optimised style. And I agree, dropping braces makes the code less easy to read. I try to compensate for this by adhering strictly to a consistent use of indentation.

    Well, I'll try to think about making my code easier to follow, at least when I write a code example.


    Maybe my use of hungarian notation also hurts readability a bit - but it makes variable names so much shorter and you can see what type they are of directly.
    Last edited by liorean; 04-02-2003 at 10:46 PM.
    liorean <[lio@wg]>
    Articles: RegEx evolt wsabstract , Named Arguments
    Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
    Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards

  • #8
    Regular Coder
    Join Date
    Jul 2002
    Location
    Iran
    Posts
    695
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thanks liorean, now I can read better! You're right, I'm not a C/C++ coder, but I knew about the ternary operator. That part of your code that you used regular expressions to add "on" at the beginning of an event was somehow beautiful/confusing! Thanks for the explanation, I'll use some parts of them myself too About the hungraian notation, lots of ppl say it's bad and lots of them say it's fine, but well, I think if you're used to anything, you should continue that, coz you can write best in your own method.

    Brothercake, as you said your code doesn't work under IE and well, I don't think it's a good idea to add the name of the first function manually ( what's the use of a function?! ), and unfortunately I can't do it in this case. Anyways, I'm gonna take a closer look at liorean's function.

    Another question: I have a sample code that works in IE, but not in NS, do you know what's wrong with it?

    Code:
    <form>
    <input type="text" id="oopse">
    </form>
    <script>
    document.getElementById("oopse").onkeypress = function() { alert(event.keyCode) }
    </script>
    I even tried e.which instead of event.keyCode but this damn NS doesn't answer.

  • #9
    Master Coder
    Join Date
    Feb 2003
    Location
    Umeå, Sweden
    Posts
    5,575
    Thanks
    0
    Thanked 83 Times in 74 Posts
    Try replacing that function with:
    Code:
    function(e){
        e=e||window.event;
        alert(e.keyCode||e.which);
    }
    liorean <[lio@wg]>
    Articles: RegEx evolt wsabstract , Named Arguments
    Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
    Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards

  • #10
    Senior Coder
    Join Date
    Aug 2002
    Posts
    3,467
    Thanks
    0
    Thanked 0 Times in 0 Posts
    What about attachEvent and addEventListener? Both allow you to attach an indefinite number of actions to a single event handler.
    My Site | fValidate | My Brainbench | MSDN | Gecko | xBrowser DOM | PHP | Ars | PVP
    “Minds are like parachutes. They don't work unless they are open”
    “Maturity is simply knowing when to not be immature”

  • #11
    Master Coder
    Join Date
    Feb 2003
    Location
    Umeå, Sweden
    Posts
    5,575
    Thanks
    0
    Thanked 83 Times in 74 Posts
    How is iem, saf/konq, op7 and iCab support for them? Some time ago (before saf and op7), only iew and moz handled them.
    liorean <[lio@wg]>
    Articles: RegEx evolt wsabstract , Named Arguments
    Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
    Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards

  • #12
    Senior Coder
    Join Date
    Aug 2002
    Posts
    3,467
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Not sure, but I do know this. The wizards over at DHTML kitchen use a file they made regularly, global.js, that has a wicked-cool wrapper to help browsers lacking these handy methods.

    I'll be honest with you, I don't fully understand how it works, but I think I got a rough idea. Suffice to say, I didn't look at it and go "Oh, I see how they did that".
    Last edited by beetle; 04-03-2003 at 04:13 PM.
    My Site | fValidate | My Brainbench | MSDN | Gecko | xBrowser DOM | PHP | Ars | PVP
    “Minds are like parachutes. They don't work unless they are open”
    “Maturity is simply knowing when to not be immature”


  •  

    Posting Permissions

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