Question

I have an element with an event handler defined on it:

$('.element').click(function(){
    alert('I was clicked');
})

Is there a way to add - or better to EXTEND - the callback defined on click event for .element selector in order to obtain something like this?

/* In another part of my .js script I add these lines of code. 
 * Here is where I'd like to "add" or "extend" the handler with another callback */
$('.element.specific_extended_element').click(function(){
    alert('Extended click');
    /* -- execute parent handler -- */
})

The result I'd like to obtain would be similar to two alerts opened when .element.specific_extended_element is clicked:

1st alert: "Extended click";
2nd alert: "I was clicked".
Was it helpful?

Solution

One simple and direct approach is to do what you always do when you want to reuse functionality: Make it a function you can call from more than one place:

// The original handler
function originalHandler() {
    alert('I was clicked');
}

// Hooking it up, not including the special element
$('.element:not(.specific_extended_element)').click(originalHandler);

// Hooking up your additional handler
$('.element.specific_extended_element').click(function(e){
    alert('Extended click');
    originalHandler.call(this, e);
});

Live Example

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top