I call an external js file. This js file already has a (document).click function. I want to have an (document).click within the main js.
external js:
$(document).click(function() {
//do stuff
});
I do not use global variables. What's the best way to have $(document).click function in the external file and also to add an $(document).click function within the main js?
You can have both. As long as nobody stops propagation, both event handlers will run.
Do post the code if you still have any trouble.
Expanding the answer a bit: There is in fact a way (the wrong way) to do click event handlers that supports only one at a time. If you do:
element.onclick = function () {alert('a')};
And then
element.onclick = function () {alert('b')};
You will get only one alert (saying 'b'). Which is why you should never use that. This is a remnant of a time when nobody knew what they were doing. It's 2015, the less we talk about it the better.
Now, when you use the proper way of registering event handlers:
element.addEventListener('click', function () {alert('a')});
element.addEventListener('click', function () {alert('b')});
You'll get both alerts.
To clear up any confusion, it's worth mentioning that jQuery uses the same old addEventListener internally when you do $(element).click(f) or $(element).on('click', f) or however it works today.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With