Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • "libs.js" that contains functionX1 to handle the click event:

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

}

  • "index.html" that contains a button

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?

  • X1 will be implemented, X2 is ignored.
  • X1 will be ignored, X2 will be implemented.
  • X1 will be implemented, and the X2 will be implemented.
like image 375
chipbk10 Avatar asked Dec 30 '25 13:12

chipbk10


1 Answers

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();
}
like image 123
Rory McCrossan Avatar answered Jan 01 '26 02:01

Rory McCrossan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!