简体   繁体   中英

javascript: Possible to add event handler that runs after the default behavior?

I have an event handler that I would like to have executed after the default javascript handling of that event occurs.

Is this possible?

EDIT: For example: everytime a keypress event is fired, i'm logging event information about that keypress(similar to console.log). Now, when I press backspace and view the fields contents via the event handler, the value of the text field produces the value without the backspace since the event handler grabs the contents of the field before the actual removal of the last letter.

I would like, in this case, for the default backspace event to occur and then have my event handler fired upon completion.

Thanks!

I believe your problem is caused by listening for the keypress event instead of the keyup event. Basically this means that you are getting the value of the textarea before the character is put in the dom.

Try changing your keypress handler to a keyup handler.

An example would be:

$('input, textarea').keyup(function(ev) {

    console.log( $(this).val() );

});

Edit: Found this question which appears to be your exact problem.

I see that there was a different issue other than what is named in the question. In that regards, +1 Sam :).

However, I would like to address the question here, and not just the offshoot. There is a way to handle specific keypress events or default to one.

keypress bubbles. So use a global one, and then for anywhere you need it locally, use e.stopPropagation() in order to stop it from bubbling. Here is a demo of it working: http://jsfiddle.net/2EwhR/

here is the html:

<div id="d1">_</div>
<br><hr>
<div id="d2"><input id="i1" type="text" /></div>

js:

var d1 = document.getElementById("d1");
window.onkeypress = function(ev){
 d1.innerHTML = "keyCode: " + ev.keyCode;
};
var d2 = document.getElementById("d2");
var i1 = document.getElementById("i1");
d2.onkeypress = function(ev){
  d1.innerHTML = "blocked";
  ev.stopPropagation();
};

This would be a way to run custom code after the event has bubbled up to the browser, ie the typed in value would first be added to the text field, then a second later your custom function would run. You could make this a much smaller amount of time if you wish.

$("input").on("keypress", function () {
  setTimeout(function () {
    alert("new value should have been already added to text field. Now we are executing some custom stuff");
  }, 1000);
  return true;
});

working demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM