Mystical
Mystical

Reputation: 2783

Inserting an element prevents click event from firing

I have a simple form validator. When you click away from the input, it displays an error message (when necessary).

However, I have noticed a side effect. When the error message is inserted into the form, it shifts the submit button downward, which prevents the submit event from firing.

Take a look at the snippet below. This overly simplified example emulates the problem. Try clicking on the input and then the button. You'll notice that the button's click event won't fire because it is shifted downwards.

function insert() {   
  var button = document.querySelector('button');
  document.body.insertBefore(document.createElement('div'), button);
}
div {
  width: 100px;
  height: 100px;
  background-color: red;
}
<input onblur="insert()" />
<button onclick="alert()">Click</button>

How can I resolve this problem? Keep in mind that for my form validator, the button is of type submit and the event that won't fire is the form's submit event, but the same concept can clearly be applied here.

Upvotes: 0

Views: 58

Answers (2)

phentnil
phentnil

Reputation: 2279

The reason the alert() isn't firing is because the created div element is inserted with the blur event before the click event occurs. Then when the click event occurs, it doesn't register with the button because the button is moved on the page. In the example below, I added a delayInsert function to demonstrate this.

Steps:

  1. Click in the input field
  2. Click the Click button

The alert() will fire before the div is inserted.

function delayInsert() {
  setTimeout(insert, 1000);
}

function insert() {
  var button = document.querySelector('button');
  document.body.insertBefore(document.createElement('div'), button);
}
div {
  width: 100px;
  height: 100px;
  background-color: red;
}
<input onblur="delayInsert()" />
<button onclick="alert()">Click</button>

Upvotes: 1

lolBOT V9.17
lolBOT V9.17

Reputation: 147

It works for me. When I edit the txt box, the div is appended. When I click the button, it alerts. Try using js to get the data and send a xmlHTTPrequest to the php?

Upvotes: -1

Related Questions