Home > OS >  How to detect mouse click outside the form right after clicking input field
How to detect mouse click outside the form right after clicking input field

Time:05-06

I want to detect if the user click outside the form. The issue is that whenever I click first the input field then clicking outside the form, the onblur listener doesn't detect.

HTML

<form  tabindex="0" onClick="foo('inside')" onBlur="foo('outside')">
  <input id="myInput">
</form>
<p ></p> 

CSS

.foo {
  background-color: salmon;
  height: 100px;
  width: 100px;
}

.foo:focus {
  outline: 0;
}

JS

const p = document.querySelector('.p');

function foo(x) {
  p.innerHTML = x;
}

My code here

CodePudding user response:

Your code is fine but there seems to be some intermittent glitch with codepen. I deleted and re-typed "onblur" and it was fine but then wasn't.

It works as expected on the snippet tool here and on js fiddle (and sometimes on codepen)

const p = document.querySelector('.p');

function foo(x) {
  p.innerHTML = x;
}
.foo {
  background-color: salmon;
  height: 100px;
  width: 100px;
}

.foo:focus {
  outline: 0;
}
<div  tabindex="0" onClick="foo('inside')" onBlur="foo('outside')"></div>
<p ></p>

CodePudding user response:

You are using onBlur event on an form. Form doesn't have a blur event. It's only valid for input fields. But the onClick event works. It can be done in any html element.

What you want is this.

<form  tabindex="0" >
  <input id="myInput" onBlur="foo('outside')" onFocus="foo('inside')" />
</form> <p ></p> 
  • Related