john c. j.
john c. j.

Reputation: 1175

Execute event before its natural behaviour

Is there a way to execute javascript-event before it's natural behaviour?

For example, using the code below, if you press / key on your keyboard, this character will be immediately printed in the input field, and after 2 seconds, the alert will be showed. That's obviuos.

But is there a way to make alert showed before the / is printed?

<input></input>

<script>
document.querySelector("input").focus();

addEventListener("keydown", function (e) { if (e.keyCode === 191) { myFunc(e); } });
function myFunc(e) {
    setTimeout(function() {
        alert("Hello!");
    }, 2000);
}
</script>

Upvotes: 2

Views: 47

Answers (4)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Unified solution for all inputted characters on keypress event:

addEventListener("keypress", function(e) {
  var val = e.which || e.keyCode;
  e.preventDefault();
  myFunc(e.target, val);
});

function myFunc(target, val) {
  setTimeout(function() {
    alert("Hello!");
    target.value = String.fromCharCode(val);
  }, 2000);
}

Try it.

Upvotes: 1

Simon H
Simon H

Reputation: 21005

Try this - its a bit of a hack

document.querySelector("input").focus();

addEventListener("keyup", function(e) {
  console.log(e);
  //debugger;
  if (e.keyCode === 191) {
    e.target.value = "";
    myFunc(e, e.target);
  }
});

function myFunc(e, t) {
  setTimeout(function() {
    alert("Hello!");
    t.value = "/";
  }, 2000);
}
<input></input>

Upvotes: 1

KLin
KLin

Reputation: 479

Try to change

function myFunc(e) {
    setTimeout(function() {
        alert("Hello!");
    }, 2000);
}

to

function myFunc(e) {
    alert("Hello!");
}

Upvotes: 0

Niels Keurentjes
Niels Keurentjes

Reputation: 41958

The behaviour you describe is actually the default, as demonstrated here:

document.getElementById('test').addEventListener('keydown', function(e) {
  e.preventDefault();
}, true);
<input type="text" id="test">

If you cancel a keydown event, the key is not printed. Therefore the code was executed before its default action.

Upvotes: 0

Related Questions