0

I'm using the flex box justify-content setting to automatically put space between my elements on a header bar. It works really well. However, now, I've started toying around with an expanding search bar (i.e. it gets wider when the user focuses on it). This isn't a crucial part of the website, so I can easily forgo it. However, while playing around I noticed a weird behaviour happening with the button click.

If you run the fiddle below, you'll see that when you click the button without first selecting the input that the browser thinks you've clicked on the parent div. If you click again however, you'll have clicked on the actual button.

Can anyone explain why this is happening?

Also, maybe it is due to the CSS transformation, however that is there so that the div grows to the right rather than left (which is what happens when the justify-content is set to flex-end.

$(document).on("click", function(e) {
  alert('you clicked on ' + $(e.target).prop("tagName") + '.' + $(e.target).attr("class"));

});
.header-search {
  width: 4rem;
}

ul>li {
  display: inline-block;
  padding-left: 1rem;
  list-style-type: none;
}

.header-search:focus {
  width: 7rem;
}

.header-search-bar:focus-within {
  margin-left: -3rem;
  transform: translateX(3rem);
}

.container {
  margin-top: 25px;
  width: 75%;
  display: flex;
  align-items: stretch;
  flex-wrap: wrap;
  justify-content: space-between;
}

.left,
.right {
  display: flex;
  align-items: center;
}

.right {
  justify-content: flex-end;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="left">
    LEFT CONTENT

  </div>
  <div class="right">

    <ul>
      <li>Item 1</li>
      <li>Item 2</li>
      <li class="header-search-bar">

        <div class="parentDIV">
          <input type="search" class="header-search" placeholder="Search..." name="q" value="">
          <button type="submit" class="submitBTN" id="searchSubmit">SUBMIT
  </button>
        </div>


      </li>
    </ul>

  </div>
</div>
CircularRecursion
  • 450
  • 1
  • 6
  • 18
  • 1
    This is possibly a duplicate of [Prevent firing focus event when clicking on div](https://stackoverflow.com/questions/8735764/prevent-firing-focus-event-when-clicking-on-div). TL;DR, listen to the `mousedown` event instead of `click`. – Rowan Baker-French Apr 16 '19 at 23:52
  • actualy its when you click between the search and the button – godfather Apr 17 '19 at 00:27

1 Answers1

0

As Rowan Baker-French correctly pointed out in a comment, this is a duplicate of Prevent firing focus event when click on div.

The way round it is to do:

$(document).on("mousedown", function(e) {
  e.preventDefault();
  alert('you clicked on ' + $(e.target).prop("tagName") + '.' + $(e.target).attr("class"));
});
CircularRecursion
  • 450
  • 1
  • 6
  • 18