-1

i have legacy js code which i dont what to touch defined in script A.js .. it have simple onlick event and function attahced to it

$(document).ready(function () {
    //jquery onclick 
    $("#create_button").click(function (e) {
    ..... 
    }
}    
    //html
     <button class="btn btn-primary" id="create_button"
                                            name="create_button">
                                        Create New app
                                    </button>

Then to add functionality to this button im defining in doing this is loading in my second script script B.js which comes after A.js

$(window).on('load', function(){
    document.getElementById("create_button").addEventListener("click", () => {
                                      self.MyFirstFunction()
                     }, false);

}

my question is how can i defined that self.MyFirstFunction() will allways triggred first ?

I_love_vegetables
  • 1,575
  • 5
  • 12
  • 26
user63898
  • 29,839
  • 85
  • 272
  • 514
  • Does this answer your question? [How do you force your Javascript event to run first, regardless of the order in which the events were added?](https://stackoverflow.com/questions/13979961/how-do-you-force-your-javascript-event-to-run-first-regardless-of-the-order-in) – Cristik Mar 29 '22 at 16:42

2 Answers2

1

You can set the useCapture flag of the eventListener to give it the highest priority over other eventListeners.

In your case:

scriptB.js

$(window).on("load", function () {
    document
        .getElementById("create_button")
        .addEventListener("click", () => self.MyFirstFunction(), true);
});

Demo:

let button = document.querySelector("#button")

button.addEventListener("click", () => {
  console.log("I was added first")
})

button.addEventListener("click", () => {
  console.log("I was added second")
}, true)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="button">Demo Button</button>
lejlun
  • 4,140
  • 2
  • 15
  • 31
1

set useCapture to true when adding event listener to the element:

For event listeners attached to the event target, the event is in the target phase, rather than the capturing and bubbling phases. Event listeners in the “capturing” phase are called before event listeners in any non-capturing phases.

$('#element').click(function(){
  console.log("first registered Handler in source code")
})

document.getElementById("element").addEventListener("click",function(e){
console.log("second registered Handler in source code")},true); // Notice the last argument is true 
#element{
  width:200px;
  height:100px;
  background:lightgreen;
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="element"></div>
Alan Omar
  • 4,023
  • 1
  • 9
  • 20