jeff
jeff

Reputation: 1020

why event.target does not fire on the following code while simple click event handler works?

Following is the code

(function(window){
  
  var form = document.getElementById('form_element'),
      form2 = document.getElementById('form_element2'),
      container = document.getElementById('container');
  
  window.addEventListener('mouseup', getAlert);
  
  function getAlert(event) {
    if(event.target === form) {
      alert('I clicked on a form');
    }
  }
  
  form2.addEventListener('click', function() {
    container.innerHTML = '<h1>I am however working</h1>';
  });
  
})(window);
#container {
  height:400px;
  width:400px;
  background:red;
}

#form_element {
  display:inline-block;
}
<form action="" id="form_element">
  <input type="text" placeholder="Enter here..."/>
</form>

<form action="" id="form_element2">
  <input type="text" placeholder="Enter here..."/>
</form>

<div id="container">
  <h2>Something goes here</h2>
</div>

Could you help me with this, with some explanation? Does this differ in jquery selector?

I am stuck with such small situations. Could you please help me work it out.

Thanks

Upvotes: 1

Views: 198

Answers (1)

nick zoum
nick zoum

Reputation: 7315

The problem is that the target when the mouse goes up is the input element and not the form

Here are some ways to solve your problem

  1. Check if the target is the input element

    window.addEventListener("mouseUp", getAlert);
    function getAlert(event) {
        if (event.target === form.firstElementChild) {
            alert('I clicked on a form');
        }
    }
    
  2. Add the listener to the form so that there is no need to check anything

    form.addEventListener("mouseUp", getAlert);
    function getAlert(event) {
        alert('I clicked on a form');
    }
    
  3. Check if the target is the form OR if the target is an element of the form

    window.addEventListener("mouseUp", getAlert);
    function getAlert(event) {
        if (event.target === form || form.contains(event.target)) {
            alert('I clicked on a form');
        }
    }
    
  4. Use CSS to add some padding to the form so you can have space to click the form without clicking the input

    #form_element {
        padding: 20px;
    }
    
  5. Use CSS to make the input element "invisible" to the mouse

    #form_element>input {
        pointer-events: none;
    }
    

Upvotes: 1

Related Questions