Question

This is an example on CodePen.

Here's the code anyway:

HTML:

<div contenteditable="true" id="mydiv"></div>

jQuery:

$(function () {
  $("#mydiv").keydown(function (evt) {
    if (evt.which == 13) {
      evt.preventDefault();
      alert('event fired');  
    }
  });
});

Why won't the evt.preventDefault() method work?

Was it helpful?

Solution

The preventDefault call just keeps the default event handler from running. If you want to skip any code after the point where you have evt.preventDefault(), put a return false after it.

$(function () {
    $("#mydiv").keydown(function (evt) {
        if (evt.which == 13) {
            return false; // <-- now event doesn't bubble up and alert doesn't run
            alert('event fired');  
        }
    });
});

Also, as mentioned by squint, you can use stopPropagation and preventDefault to achieve the same effect.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top