Peter
Peter

Reputation: 334

jquery javascript override / extend event

I have an element with event set, e.g.

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

Now, I want to intercept this event and run some other script in addition to default one. I wrote 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 is not working as I expected. Anybody knows how to make this working?

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

What if the keyup event for the input is not inlined, but set using jQuery bind? I want to override/extend the default behaviour, I do not want to change the base code.

Upvotes: 4

Views: 3120

Answers (3)

Mrchief
Mrchief

Reputation: 76258

Here's a working fiddle: 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. Also, I commented out some parts as you don't need them.

Upvotes: 2

CodeReaper
CodeReaper

Reputation: 6155

I have forked your fiddle to here : http://jsfiddle.net/xdaTH/

I have turned on jQuery instead of MooTools, but also using .get(0) to get the actual dom element which has a onkeyup function defined.

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");
  });

});

Upvotes: 1

DanyZift
DanyZift

Reputation: 687

Create your own custom event and then trigger it:

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

$('#txt').trigger('custom', ['Custom', 'Event']);

You can find out info on it here: jquery trigger

Upvotes: 0

Related Questions