user1921267
user1921267

Reputation: 79

Condition does not work

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();
});

http://jsfiddle.net/kgj4uw6f/

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

Answers (3)

Vibhesh Kaul
Vibhesh Kaul

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

Jo&#227;o Cerqueira
Jo&#227;o Cerqueira

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

Paul Roub
Paul Roub

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

Related Questions