1

I have a page containing several different scripts, and there is some click event binding to the same element. So I encounter an issue with the event order. There is code. (for the more the script A and B is unknown).

I want execute Script A after Script B is executed.

//Script A
$('a').click(function (){
    alert('1')
})

//Script B
$('a').click(function (){
    alert('2')
})

Any advice? Thanks

Todd Mark
  • 1,847
  • 13
  • 25
  • 2
    Your question is a little unclear. If the scripts are unknown, then why does the order matter? Are you saying there's one particular script that you *do* know and you always want it to execute last? –  Jul 08 '15 at 16:06
  • @squint In other word, I want it to be execute first. – Todd Mark Jul 08 '15 at 16:10
  • That's difficult. I think if you make sure your script runs first, it may get bound first and therefore execute first, but I don't know. What's the actual problem that seems to rely on the order of bound handlers? –  Jul 08 '15 at 16:12
  • ...do you control the code in the other scripts? Can they be changed? –  Jul 08 '15 at 16:14
  • @squint The different thing is the whole code is not controlled by me, I want my click event is be execute before others code. So I abstract the question. But I haven't do it better. – Todd Mark Jul 08 '15 at 16:21
  • Have you tried any of the solutions in http://stackoverflow.com/questions/290254/how-to-order-events-bound-with-jquery to see if they work? – Brant Olsen Jul 08 '15 at 16:40

1 Answers1

3

Let's say that you have two scripts: script1.js and script2.js. Both of them attach event handlers to the same element. script1.js is currently loaded in before script2.js.

Right now, the handler in script1.js will execute before the handler in script2.js. There are a few ways of changing this:

  1. Swap the load order. Make sure that script2.js loads before script1.js.
  2. Attach the handler in script1.js to a unique event and trigger it from script2.js.

Example:

// script1.js
$('a').on('custom-event', function(e) {
  // do stuff
});

// script2.js
$('a').click(function(e) {
  // do stuff
  $(this).trigger('custom-event', e);
});
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91