0

I have the following situation:

In a html page i have a dynamically generated button, similar to:

<div id='myButton'></div>

This html page includes a script (e.g., A.js), that handles most of the functionality of the site, and in this script the button is being bound to an handler:

$("#myButton").bind("click", function(){
foo();
});

So far its simple. Now, only in a particular situation, i need the same button to execute a second function. This has to be done through another script, dynamically generated and injected inside the html site. So the html will look similar to this:

<script type=text/javascript src=A.js></script>
<script type=text/javascript>
//Dynamically generated script
</script>

I do not want to override the previous function, i still need that to be executed, but also i need this function to be executed before the first one. And the way scripts are included on the site cannot be changed.

So, I have written the following (inside the second script tag):

    $("#myButton").bind("click",
     function(){
          bar(); // I still want foo() to be executed but after this is executed first. 
});

Is it possible to do something like this? Note that i do not have control on how scripts are included on my site. Altering that order is not possible.

2 Answers 2

1

You can still have more bindings to the same event

http://jsbin.com/iyewu5/edit

they will be fired sorted by what was the first in the code

so you can have:

$("#myButton").bind("click", function() { foo(); });

and in other script

$("#myButton").bind("click", function() { bar(); });

this will act as

$("#myButton").bind("click", function() { foo(); bar(); });

as long as you place them under $(document).ready( function() {});

Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunately, i cannot control how the event is bound in A.js. This is done by the CMS. I could just add the new click binding, and need to find a way to execute this click first before the one added by the cms.
it's a matter of what is first, just swap the position... of tell us what are you exactly trying to accomplish with live code for a better help.
0

why not just combine bolt foo,bar into that function..

$("#myButton").bind("click", function(){
 bar();
 foo();
});

or you may implement the foo() as callback function.

1 Comment

Yes, but i am not adding the foo(), its has been added by the system (the CMS in this case) and i cannot alter that behavior!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.