I have a simple button in HTML like this:
<input type='button' id='btnPrint' value='Print' onclick="changeStylesheet();" />
This button already contains a onclick event handler. What I m trying to achieve here is to be able compose the onclick event handler for same the button. I would like to add second method that tracks how many times the button was hit.
some approaches:
First: Append another function call in HTML as per inline event registration.
<input type='button' id='btnPrint' value='Print' onclick='changeStylesheet();trackThis();>' />
This is the easiest way to go but not feasible in my situation.
Second: Grab the onclick event and check if it is undefined. Then, recompose the event handler with anonymous function using JavaScript native syntax.
var elem = document.getElementById('btnPrint');
var existingHandler = **elem.onclick ? elem.onclick : function () {};**
elem.onclick = function () {
trackThis();
existingHandler();
};
Third: Though above approaches work, I m curious to learn the way to do above #2 approach but with jQuery syntax.
var elem = $('#btnPrint');
var existingHandler = **elem.click ? elem.click : function () {};**
elem.click(function () {
trackThis();
existingHandler()
});
What is happening with #3 solution in mine is that I m getting
Uncaught TypeError: Object [object Window] has no method ‘trigger’
error.
Any hints will be very appreciated.
If both handlers are to be attached in jQuery then simply set two click handlers. Internally, jQuery implements an “observer pattern” such that it aggregates handlers and will execute them sequentially in the order they were added.
These statements need not be consecutive or even in the same scope.
The same principle applies if a handler is already specified in the HTML. jQuery will simply execute any additional handlers after the original.
HTML:
jQuery:
See fiddle
EDIT …
It is also possible to revere the order such that the original handler executes after a handler attached in jQuery :
See fiddle