Reputation: 1223
i want to show and hide some element based on click. i have two button , when you click one of the button it will show a form and if you click the other button it'll show another form. now what i want if someone has clicked the button it'll show the form and then if he click somewhere else that form should be hidden. i did he first part by following code
$(document).ready(function(){
$("#login_btn").click(function(){
$("#login_form").toggleClass("hide");
$("#signup_form").addClass("hide");
});
$("#signup_btn").click(function(){
$("#signup_form").toggleClass("hide");
$("#login_form").addClass("hide");
});
$(".container > :not(#login_btn)").click(function(){
$("#signup_form").addClass("hide");
$("#login_form").addClass("hide");
});
});
now i want to hide those form when clicked somewhere else. I tried with $('body > :not('#login_form,#signup_form'), but it also disable the button's activity,when i click the button it doesn't show the form. I already searched similar question in stackoverflow and other places but none of the solution worked. so anybody know how to do this?
Upvotes: 0
Views: 61
Reputation: 17340
You can hide any elements by doing a quick search for where you clicked. What thou want to know is: have I clicked in the document? Have I clicked on the button? Otherwise, have I clicked on a form? If I clicked on a form, then don't close it. If I clicked outside a form, close the form.
$(document).click(function(event){
var target = $(event.target);
/* if the target is a button, don't continue as we want to keep its click */
if(target.attr("id") === "login_btn" || target.attr("id") === "signup_btn"){
return;
}
/* lets see if the target, or any of its parents, has the form id we are looking for */
/* if it doesn't, hide that form */
if(!target.closest("#login_form").length){
$("#login_form").hide();
}
if(!target.closest("#signup_form").length){
$("#signup_form").hide();
}
});
Sorry, the click should be on the document and the IDs I used were incorrect. All form-ids are now using underscore instead of dashes (i.e. login_form). I also used a wrong id in the third if, pointing to the login form while I was checking the signup_form. I've amended, tried and it does work.
Upvotes: 2