chipbk10
chipbk10

Reputation: 5955

Is it posible to implement 2 functions for the same event handler in Javascript?

I am quite new to Javascript or JQuery. I have a quite complete HTML resource, in which a button element has a function X1 to handle its click event.

Now, I don't want to modify any thing from the existing HTML resource, but want to add my function X2 when the user clicks on the button. My purpose is after functionX1 is implemented, my functionX2 will be implemented.

I wrote functionX2 in a separate javascript file, and include in the index.html.

Is it posible?

-------------------------------- EDIT ---------------------------------

The existing html resource looks like follow:


$('#button').on('click', function() {
   //-do X1 here
   ....

}


head

script src="libs.js"

/head

body

div id="button"

/body

Now, I don't want to modify anything from "libs.js", I write a separate javascript file "mylibs.js", in which create another function to handle the button's click event.


$('#button').on('click', function() {
   //-do X2 here
   ....

}

In the index.html, I include my js file


head

script src="libs.js"
script src="mylibs.js"

/head

body

div id="button"

/body

So does it serve my purpose: do X1 and then do X2 when the button is clicked?

If I include as above, when the button gets clicked, one of the following cases will happen?

Upvotes: 2

Views: 107

Answers (3)

Michel
Michel

Reputation: 4157

[edit] As Stefan correctly stated: jQuery can handle multiple eventhandlers and fires them in the order they are bound.

So just add

$('#foo').click(function () {
   X2();
});

after the original handler was attached, and you'll be ok.

Fiddle


[I'll leave this for future reference, but it's obsolete]

There is an option, but it is hack, prone to errors and I would recommend Rory's first solution, but here we go:

//the original click
$('#foo').click(function () {
   X1();
});

//add an additional MOUSEUP listener
//note that mouseup fires before click, so there has to be a timeout
$('#foo').mouseup(function () {
    setTimeout(function () {
        X2()
    }, 200);
});

function X1() {
    //run X1
}

function X2() {
   //run X2
}

Here is a fiddle

Upvotes: 1

user2844991
user2844991

Reputation:

$("#my-btn").on("click", function () { alert(1); });
$("#my-btn").on("click", function () { alert(2); });

This is already supported in jQuery.

Upvotes: 3

Rory McCrossan
Rory McCrossan

Reputation: 337550

This is easily possible. Dependent on how the code is structured you would just need to place the call to your functionX2 after the call to functionX1 in the anonymous handler:

$('#foo').click(function() {
    functionX1();
    functionX2();
});

Alternatively, you can call functionX2() at the end of functionX1():

var functionX1 = function() {
    // your logic...

   functionX2();
}

Upvotes: 6

Related Questions