Reputation: 21
i have a problem with js
i have a icon and a form my form is appear when i click on icon
i want to my form was hide when clicked outside form now when i click on icon to show my form , js hide my form becuase it outside of my form any body can help me?
mycode for show/hide when click on icon:
$(document).ready(function(){
$("#icon").click(function(){
$("#form-subscribe").animate({
height: 'toggle'
});
});
});
and my code for hide form when clicked outside of form:
$(document).ready(function()
{
$("#main").mouseup(function(e)
{
var subject = $("#form-subscribe");
if(e.target.id != subject.attr('id') && !subject.has(e.target).length)
{
$("#form-subscribe").animate({
height: 'hide'
});
}
});
});
Upvotes: 1
Views: 118
Reputation: 7618
You can accomplish this by inspecting the e.target
DOM node inside of a jQuery $.contains()
method.
Link to jQuery Contains Method: https://api.jquery.com/jQuery.contains/
Here is a JSFiddle: https://jsfiddle.net/iamjpg/eq43eve5/
HTML:
<div>
<i class="fa fa-plus" aria-hidden="true"></i>
</div>
<form id="form">
<div>
<input>
</div>
<div>
<input>
</div>
<div>
<input>
</div>
</form>
Javascript:
$('.fa').on('click', function() {
$('#form').show();
})
$(document).on('click', function(e) {
// If e.target is not inside of the form container AND not
// the icon triggering the initial showing of the form,
// hide the form div.
if (!$.contains(document.querySelector('#form'), e.target) && !$(e.target).hasClass('fa')) {
$('#form').hide();
}
})
Upvotes: 1