user3548039
user3548039

Reputation: 53

Events in javascript

I want to open a form on click of modify. I also want form to disappear when i click outside the form. When i use mouseleave event for that, the form is getting open and close automatically and i am failing to fill the form. I am not getting which event to use here.

JS

$(document).ready(function() {
    $("#div1").load("compare-form-site.html");
});

$( ".m-search" ).click(function() {
    $( "#modify" ).show( "blind",700 );
    $( "#bank" ).hide();
    $( ".slider" ).hide();
    $( "#type" ).hide();
    $( "#sort" ).hide();
});

$(".m-search").mouseleave(function(){
    $('#modify').hide( );
});

HTML

<ul>
    <li class="m-search">
         Modify Search 
         <i class="fa fa-search-plus" aria-hidden="true">
         </i>
         <div id="modify" class="modify">
             <div id="div1">
             </div> 
         </div>
    </li>
  </ul>

Upvotes: 0

Views: 80

Answers (3)

pleinx
pleinx

Reputation: 626

A working fiddle would be better for all to help you.

Here is an working example that should be help you:

// open the form
$('.modify').on('click', function(e) {
	$(this).parent().find('.dialog').fadeIn();
});

// close the form (button inside form)
$('.close').on('click', function(e) {
	$(this).parents('.dialog').fadeOut();
});

// hide the form if you click outside the form
$(document).mouseup(function (e) {
    var container = $(".dialog");
    if (!container.is(e.target) && container.has(e.target).length === 0) {
        container.hide();
    }
});
ul li button {
  display: block;
}

.dialog {
  display: none;
  position: absolute;
  top: 10%;
  bottom: 10%;
  left: 10%;
  right: 10%;
  background: blue;
}

.dialog .close {
  float: right;
  color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul>
  <li>
    Modifiy Search
    <button class="modify">Test</button>
    <div class="dialog">
      <span class="close">Close me</span>
      Im a test dialog
    </div>
  </li>
</ul>

Upvotes: 1

Shubham Khatri
Shubham Khatri

Reputation: 282120

You can compare to the target element and check if you click outside the form or in it. I f outside then hide the form.

$(document).on('click', function(e){
var $target = $('.modify');
if($target.is($(e.target)) && !$trigger.has(e.target).length) {

  $('.modify').hide();
}

})

Upvotes: 2

Wolfgang
Wolfgang

Reputation: 896

mouseleave doesn't react on click but on the current pointer position. You have to add a click (mousedown) listener to e.g. document to listen to click events outside

Upvotes: 0

Related Questions