OK to use same event listener in dom ready and window load for jQuery?

126 Views Asked by At

Ive used when a select list's option is changed as an event listener, with something like this:

$('#mySelect').change(function() {
        functionToRun();
});

Is it OK to use the event listener more than once? So something like below. I know for this exact example it makes no sense, but for more complicated code with conditionals at work it would be easier for me to maintain my code if I used the event listener twice.

$('#mySelect').change(function() {
        functionToRun();
});

//other code

$('#mySelect').change(function() {
        functionToRunTwo();
});

Also, I have some code that runs on dom ready and some that runs on window load. Is it OK to use the same event listener in both instances?

2

There are 2 best solutions below

0
Salman A On BEST ANSWER

It will work as expected: both event listeners will be fired and there is certainly no problem with that. From jQuery.bind() (which is called internally by jQuery.change()):

When an event reaches an element, all handlers bound to that event type for the element are fired. If there are multiple handlers registered, they will always execute in the order in which they were bound. After all handlers have executed, the event continues along the normal event propagation path.

I am not sure if this answers your second question.

0
gabitzish On

You can do that, but if you want to use the function depending on the context, make sure you unbind the function you don't need.