The problem is that you don't stop the event from propagating.
When you click the button it actually hide the element at first, but the event propagate up to the parent element, at which you catch the click and show it again. It goes so fast it looks like nothing is happening, but actually when you click on #b2
, the elements get hidden, the event then bubble up to the parent #b1
, to which you have attached click-event listener to show the content.
Therefor, you need to use .stopPropagation()
on #b2
.
$(document).ready(function(){
$('#b1').click(function(){
$('.content').show();
});
$('#b2').on("click", function(e){
$('.content').hide();
e.stopPropagation();
});
});
What you need to do is to pass the click event to the call-backfunction (declared e
in my example) and then call stopPropagation()
on it to make sure that it doesn't bubble up to the parent element.
Here is a working example: http://jsfiddle.net/jTgRF/64/
Note I use .show()
and .hide()
, which is exactly the same as what you do with .css()
, but is more readable in my opinion.
Edit:
As noted by Venu in his answer, the content will show if you click on the black-area as well, not just the "show content"-text. The easiest way to solve that would be to just move the id="b1" attribute from the div
with class content and put it on the a
-element instead.
See my updated fiddle: http://jsfiddle.net/jTgRF/65/