I want to show and hide one div as below:
$('#Div1').click(function () {
if ($("#Div2").hidden) {
$("#Div2").show(500);
}
else {
$("#Div2").hide(1000);
}
});
this code does not work.
and i want to hide div2 with clicking on empty sapce of page how can i do that and where is my code is wrong?
Answer: Use the jQuery :visible Selector You can use the jQuery :visible selector to check whether an element is visible in the layout or not. This selector will also select the elements with visibility: hidden; or opacity: 0; , because they preserve space in the layout even they are not visible to the eye.
The hide() is an inbuilt method in jQuery used to hide the selected element. Syntax: $(selector).
You can use .is(':visible') selects all elements that are visible.
hidden
is not a property of a jQuery object. Try is(':hidden')
$('#Div1').click(function () {
if ($("#Div2").is(':hidden')) {
$("#Div2").show(500);
}
else {
$("#Div2").hide(1000);
}
});
If the timings were the same you could simply use toggle()
which does hide
or show
based on the current visibility.
$('#Div1').click(function () {
$("#Div2").stop().toggle(500);
});
And as @A. Wolff suggests, to allow for multiple clicks, use stop
as well to halt any existing animation in progress:
$('#Div1').click(function () {
if ($("#Div2").stop().is(':hidden')) {
$("#Div2").show(500);
}
else {
$("#Div2").hide(1000);
}
});
Part 2:
To hide the div when you click anywhere else on the page, listen for click on document
:
e.g.
$(document).click(function(){
$("#Div2").stop().hide(1000);
});
for this to work properly though, you cannot allow the click on div1 to propagate to document so change the first part to also use stopPropagation()
on the first event argument:
$('#Div1').click(function (e) {
e.stopPropagation(); // stop click propagating to document click handler
if ($("#Div2").is(':hidden')) {
$("#Div2").show(500);
}
else {
$("#Div2").hide(1000);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With