jeff
jeff

Reputation: 1020

Why does the following Jquery event.target does not work properly

Following is my code in question

(function($) {
  'use strict';
  var button = $('#open_button');
  var box = $('#dropdown');

  function init() {
    eventsInit();
  }

  function eventsInit() {
    box.hide();
    button.on('click', open);
  }

  function open(event) {
    if (event.target !== button[0]) {
      box.hide();
    } else {
      box.show();
    }
  }

  init();
})(jQuery);
body,
html {
  padding: 0;
  margin: 0;
}

#container {
  height: 100px;
  width: 800px;
  margin: 0 auto;
}

h1 {
  color: white;
}

#dropdown {
  height: 600px;
  width: 800px;
  background-color: black;
  margin: 0 auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
  <form action="" id="open_button">
    <input type="text" placeholder="Enter the text" />
  </form>
</div>

<div id="dropdown"></div>

I need to dropdown when I click on the input form input element and close it when I click outside.

My code I believe it says, if the click target is not the button, close the dropdown, else show.

Could someone explain, why doesnt it work ?

Upvotes: 0

Views: 59

Answers (1)

Daniel Beck
Daniel Beck

Reputation: 21475

(event.target !== button[0]) is always true.

  • event.target is the <input> field.
  • button[0] is the <form> element.

You could move the #open_button id to the input field, that would cause the box to appear when the user clicks the input field -- but then the box would never disappear (because your if condition would never return true.)

What you really want are focus and blur handlers on the input field, to show and hide the box respectively:

$('#open_button input').on('focus', function() {
  $('#dropdown').show()
}).on('blur', function() {
  $('#dropdown').hide()
});

// added to answer per comment below:
$('#dropdown').on('mousedown',function(e) {
  e.preventDefault() // prevent input field from losing focus when user clicks inside the box
});

$('#dropdown').hide();
#dropdown {
  height: 600px;
  width: 800px;
  background-color: black;
  margin: 0 auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
  <form action="" id="open_button">
    <input type="text" placeholder="Enter the text" />
  </form>
</div>

<div id="dropdown"></div>

Upvotes: 1

Related Questions