Reputation: 79
Here is my code:
HTML:
<div id="a">
aaa
</div>
<div id="b">
<button>hide aaa</button>
</div>
<a href="#">link</a>
JS:
if($('#a:visible').length > 0) {
$('a').click(function() {
alert('a');
});
}
$('button').click(function () {
$('#a').hide();
});
If I click "hide aaa" and then I click on the link, alert is shown. I don't want to show the alert when #a is hidden. How can I change my code?
Upvotes: 0
Views: 45
Reputation: 2613
Here's another way of doing it! You can check the visibility of an element using $(element).is(":visible")
.
$('a').click(function() {
if($('#a').is(":visible")) {
alert('a');
}
});
$('button').click(function () {
$('#a').hide();
});
Upvotes: 1
Reputation: 563
I got it working changing your condition to inside the click event, like so:
$('a').click(function() {
if($('#a:visible').length > 0) {
alert('a');
}
});
$('button').click(function () {
$('#a').hide();
});
http://jsfiddle.net/kgj4uw6f/2/
Upvotes: 1
Reputation: 36438
It's inside-out. You have to check visibility when the click happens.
$('a').click(function() {
if ($('#a:visible').length > 0) {
alert('a');
}
});
$('button').click(function() {
$('#a').hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="a">
aaa
</div>
<div id="b">
<button>hide aaa</button>
</div>
<a href="#">link</a>
JS:
Upvotes: 2