CS_2013
CS_2013

Reputation: 1168

Is it possible to set multiple functions for one onkeypress event

I have this:

signin_input.onkeypress = function()
{
    label.style.opacity = 0;
}

but sometimes I want to run additional code so I overwrite it with this:

signin_input.onkeypress = function( event ) 
{
    signin_label.style.opacity = 0; // just add in previous function here
    if( event.keyCode === 13 )
    {
        new ControlType( 'signin' ).invoke();
        return false; 
    }
}

and just include the one line from the old function in the new function.

However, this is a bit inefficient as I write to onkeypress twice.

Is there a way to have both run. Is there some sort of internal JavaScript construct that would allow this.

Upvotes: 0

Views: 2305

Answers (2)

gabitzish
gabitzish

Reputation: 9691

I understand you are doing something like this:

signin_input.onkeypress = function1;
signin_input.onkeypress = function2;

You could do something like this:

signin_input.onkeypress = function(){
    if (condition1) function1();
    if (condition2) function2();
};

Upvotes: 1

Parth Thakkar
Parth Thakkar

Reputation: 5475

Start reading about DOM events...setting properties of elements is the ancient way...use addEventListener() or removeEventListener() for normal (meaning not IE family). Or use attachEvent() or detachEvent() for IE6 ( and I suppose IE7 too )

Best way...use some js library, I recommend jQuery.

Upvotes: 2

Related Questions