I want to make a generic plugin, that has the following logic:
- Look for #add-to-cart button Save previously attached click handler(Idon't have access to this code)
- Attach plugin's click handler, that shows popup with email opt-in.
- After successful opt-in trigger the original click handler.
I don't have access to the website's code, so I have to make a generic solution.
My implementation looks like this:
var $addToCart = $('#add-to-cart');
var origClickHandler = $addToCart.click;
$addToCart.off('click').on('click', function() {
// code to show opt-in popup ...
var $optinButton = /* ... */ ;
$optinButton.click(function() { // binding opt-in button to original click handler
origClickHandler.apply($addToCart);
});
});
But I'm getting error on the line origClickHandler.apply($addToCart)
:
jquery-2.1.1.min.js:4 Uncaught TypeError: this.on is not a function
at HTMLButtonElement.n.fn.(anonymous function) (http://www.myshop.com/js/jquery-2.1.1.min.js:4:4893)
Update
- My intent is to bind my plugin's click handler that will further call the original click handler(and not replace the original click handler entirely)
- I tried to replace
.apply()
with.call()
and got the same error. - I tried to replace
origClickHandler.apply($addToCart);
with$addToCart.off('click').on('click', origClickHandler); $addToCart.click();
and got the same error as well
Update 2
I accomplished what I wanted by cloning the button and hiding the original button:
var $addToCart = $('#add-to-cart');
var $addToCartClone = $addToCart.clone(false); // false - not copying the events and handlers
$addToCart.before($addToCartClone).hide();
$addToCartClone.click(function() {
// code to show opt-in popup ...
var $optinButton = /* ... */ ;
$optinButton.click(function() { // binding opt-in button to original click handler
$addToCart.click();
});
});
It seems like when I call .off('click')
jquery disables the click handler that was attached and I can't use it anymore. I don't know the reason, but it should work.
I will leave the question unanswered in case anyone finds the reason why original click handler stops working after calling .off('click')
.