Jquery javascript override / extend event

I have an element with a set of events like

<input type="text" id="txt" onkeyup="javascript: alert('keyup');" /> 

Now I want to intercept this event and run another script in addition to the default. I wrote the following code:

 jQuery(document).ready(function(){ var old = $("#txt").keyup; $("#txt") .unbind('keyup') .attr('onkeyup', '') .each(function() { this.onkeyup = null; }); $("#txt").keyup(function(event){ alert("before old call"); //old.call($(this)); alert("after old call"); }); }); 

But it does not work as I expected. Does anyone know how to make this work?

Link to fiddle: http://jsfiddle.net/p5JeA/

What if the keyup event for input is not enabled but set using jQuery bind? I want to override / extend the default behavior, I don't want to change the base code.

+4
source share
3 answers

The fiddle works here: http://jsfiddle.net/mrchief/p5JeA/2/

 var old = $("#txt")[0].onkeyup; $("#txt")[0].onkeyup = null; // or function () {}; // or $("#txt").removeAttr('onkeyup'); 

jQuery was not included in the resources. In addition, I commented on some parts, since you do not need them.

+2
source

I unwound your fiddle here: http://jsfiddle.net/xdaTH/

I included jQuery instead of MooTools, but also used .get (0) to get the actual dom element that has a specific onkeyup function.

script:

 jQuery(document).ready(function() { var old = $("#txt").get(0).onkeyup; $("#txt").unbind('keyup').attr('onkeyup', '').each(function() { this.onkeyup = null; }); $("#txt").keyup(function(event) { alert("before old call"); old.call(this); alert("after old call"); }); }); 
+1
source

Create your own custom event, and then fire it:

 $('#txt').bind('custom', function(event) { alert("before old call"); //old.call($(this)); alert("after old call"); }); $('#txt').trigger('custom', ['Custom', 'Event']); 

Here you can find out about it: jquery trigger

0
source

All Articles