0

I have this code the target is to put it in a hidden menu (contains div in the code) When after a click the date picker will show up, then I add the date to it and after that on blur, some elements will be created. The problem is that I want the date picker to be hidden and shown after a click on a div but this will cause the blur to run 3 times instead of one if I put the blue alone right in your face it acts normal, any idea how to prevent this triple-action from happening? and create the needed element once

let link = document.querySelector('.date-input')

 let fatherClosest = document.querySelector('.contain')
    fatherClosest.addEventListener("click", function (e) {
    
 link.addEventListener("blur", (e) => {
 console.log(e)
 // a function that will created element on blur out form the date picker 
 
 fatherClosest.insertAdjacentHTML('afterbegin', '<div class="cla">hi</div>')
 })
 })
.cla {
height: 20px;
width: 120px; 
background-color:gray;
}
<div class='contain'>

<input class="date-input" type="date" value="">

</div>
Dave Yu
  • 315
  • 4
  • 15
Richardson
  • 1,804
  • 10
  • 38

1 Answers1

1

You are nesting your event listener attachment code. On every onclick you are adding a new blur event listener.

The below code adds the event listener for both elements only once.

let link = document.querySelector('.date-input')
let fatherClosest = document.querySelector('.contain')

   fatherClosest.addEventListener("click", function (e) {

  });
    
 link.addEventListener("blur", (e) => {
 console.log(e)
 // a function that will created element on blur out form the date picker
fatherClosest.insertAdjacentHTML('afterbegin', '<div class="cla">hi</div>')
 })
 })

One more thing you could do is in your existing code before adding the 'blur' listener, remove all listeners of that type. Stack overflow link

Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39