简体   繁体   中英

Toggle and Hide Login form when users click anywhere using jquery

So I have a Login form within a li tag.

HTML

<div class='container'>
    <ul class="pull-right">
        <li><a href="#" class="nav-bar">A</a></li>
        <li><a href="#" class="nav-bar">E</a></li>
        <li><a href="#" class="lion">Login</a>
            <div class="eagle form">
                <form>
                    ...
                </form>
            </div>
        </li>
    </ul>
</div>

I want to show() the form when users click on login , and hide() the form when users click elsewhere, using jquery.

I use this jquery code after read this answer: How to hide ul using jquery when users click elsewhere

JS

$(function () {
  var sesion = $('.eagle.form');
  $('.lion').on('click', function (e) {
      e.stopPropagation();
      sesion.toggle();
  });
  $(document).on('click', function (e) {
      sesion.toggle();
  });
});

However, when login form shows up and I want to interact with the fields on it, it hides again.

How can I fix the code? I think I'm missing one line.

Any suggestions to solve the problem are appreacited!

Demo

HTML:

<ul>
  <li>
    <a href="#">test</a>
  </li>
  <div class="meh">
    <li> <a href="#" class="toggleForm">Form</a>
      <ul class="form">
        <li>
          <form>
            <input type="text" />
            <input type="submit" />
          </form>
        </li>
      </ul>
    </li>
  </div>
</ul>

Js:

$(".form").hide();
$(".toggleForm").click(function() {
  $(".form").toggle();
});
$(document).on("click", function(e) {
  if ($(e.target).closest(".meh").length == 0) {
    $(".form").hide();
  }
});

Is this what you're looking for?

Using the solution from this question: Use jQuery to hide a DIV when the user clicks outside of it

$(document).mouseup(function (e) {
    var container = $('.form');
    if (!container.is(e.target)
        && container.has(e.target).length === 0) {
        container.hide();
    }

    $('HERE-GOES-li-CONTAINER').click( function(event) {
        $('.form').toggle();
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM