Reputation: 104
I am trying to make search with simple JS effects, but I am stuck at one place.
When I click on .search
the div with .s_holder
shows up, on another click it hides. The problem is, that when I click on input
field or div s_holder
- div with form hides.
<div class="search">
<div class="s_holder">
<form name="search" method="post" action="../test.php">
<input type="search" name="query" placeholder="search">
</form>
</div>
</div>
<script>
var a=true;
$('.search').bind('click',function(){
if (a==true){
$('.s_holder').show();
a=!a;
}else{
$('.s_holder').hide();
a=!a;
}
});
</script>
<style>
.search {
background-image: url("../images/writers/search.png");
background-repeat: no-repeat;
float: left;
height: 52px;
width: 52px;
margin-right: 2%;
}
.s_holder{
display: none;
width: 300px;
float: left;
background-color: rgba(17, 17, 17, 0.12);
height: 52px;
border-radius: 25px;
}
.search input[type=search]{
margin-left: 65px;
margin-top: 15px;
width: 205px;
}
</style>
Upvotes: 0
Views: 68
Reputation: 26390
The problem is less simple that what it looks like. When you show your div's content, the form and the div.s_holder come over it, intercept the clicks and prevent from clicking the original element. You need to apply the click to all elements except the input field :
(Also, here's a much simpler code, without clumsy if(a==true)
)
$('.search, .s_holder, form').click(function(e){
if(e.target != this) return;
$('.s_holder').toggle();
});
.search {
background-image: url("../images/writers/search.png");
background-repeat: no-repeat;
float: left;
height: 52px;
width: 52px;
margin-right: 2%;
border: blue solid 1px;
}
.s_holder{
display: none;
width: 300px;
float: left;
background-color: rgba(17, 17, 17, 0.12);
height: 52px;
border-radius: 25px;
}
.search input[type=search]{
margin-left: 65px;
margin-top: 15px;
width: 205px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="search">
<div class="s_holder">
<form name="search" method="post" action="../test.php">
<input type="search" name="query" placeholder="search">
</form>
</div>
</div>
http://jsfiddle.net/9zgg3o75/2/
Upvotes: 0
Reputation: 337627
You need to check that e.target
property to see if the event has bubbled up from a child element. If it has, you can stop execution:
var a = true;
$('.search').bind('click', function (e) {
if (e.target != e.currentTarget) // the click bubbled
return;
if (a == true) {
$('.s_holder').show();
a = !a;
} else {
$('.s_holder').hide();
a = !a;
}
});
Upvotes: 4