Skip to content
Advertisement

how to prevent ONBLUR event when keypress or enter?

I have used two events KEYPRESS AND ONBLUR in my input field, when the ENTER key pressed, it triggers KEYPRESS and ONBLUR as well.

Code:

JavaScript

fiddle

Note:

I need to handle keypress as well onblur event, But i need only one event should be triggered at a time.

For example:

  1. When I press enter key, myFunction should be triggered. Not onBlur.
  2. When I click outside of the input field, onBlur function should be called.

Question:

how to prevent ONBLUR event, when ENTER key is pressed.

Your suggestion will be grateful

Advertisement

Answer

You can just reset the property to no longer hold a reference to the previously stored callback function with onblur = "".

Also, don’t set up your functions as properties of window, which makes them global. Instead just declare them in the scope you want them accessible in.

However, you really should not be setting up event handlers using HTML attributes as they create spaghetti code, cause global wrapper functions to be created around your handler functions that alter this binding and don’t follow W3C DOM Event standards.

This code really should used the .addEventListener() and .removeEventListener() model:

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement