Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

256
Views
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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

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?

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!