Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hijacking onchange event without interfering with original function

I'm writing on a library I want to include on different pages who might already use the onchange event - is there any way to attach my event to onchange without removing the original one?

EDIT:

onchange on the window object not only a single element - onchange as in a hash change in the url etc. sorry if I confused them!

like image 213
Toby Avatar asked Oct 19 '25 14:10

Toby


1 Answers

If I'm correct it sounds like you want to inject new code into an existing event. This may help you if you want a pure JavaScript solution and here is a fiddle demonstrating the feature. http://jsfiddle.net/VZCve/1/

var element = document.getElementById("myElementId");

element.onchange = (function (onchange) {
  return function(evt) {
    // reference to event to pass argument properly
    evt  = evt || event;

    // if an existing event already existed then execute it.
    if (onchange) {
      onchange(evt);
    }

    // new code "injection"
    alert("hello2");
  }
})(element.onchange);

EDITED: Now that the tags are changed and you are reference jQuery in your Question

jQuery will continue to bind new functions using jQuery.change().

note the following will execute all change functions assigned

$(document).ready(function () {
  $("#myElement").change(function() { alert('executed') });
  $("#myElement").change(function() { alert('executed again') });
  $("#myElement").change(function() { alert('executed again again') });
});

When you trigger the change event for the element in the selector you will receive 3 alerts.

Note the order of the events firing is dependent on the order each function was bound to the element.

Here is a simple fiddle demonstrating the functionality in jQuery http://jsfiddle.net/VZCve/

like image 80
John Hartsock Avatar answered Oct 21 '25 03:10

John Hartsock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!