JQuery Is there something wrong with the syntax?

$('#buttons1').on('click', function(event) { $('#button1content').toggle('show'); var wasVisible = $("#button1content").is(":visible"); if(!wasVisible) { $("#buttons1").css("opacity", "0.5"); } }); 

Toggle works fine, but everything inside the if statement fails when #button1content no longer displayed. boo. It may be another piece of my code that messed it up, but I only want to know if there is something wrong.

+5
source share
2 answers

your wasVisible variable wasVisible always return true

  • you can put toggle in the last part.

You can reorder your code as follows.

 $('#buttons1').on('click', function(event) { var wasVisible = $("#button1content").is(":visible"); if(!wasVisible) { $("#buttons1").css("opacity", "0.5"); } $('#button1content').toggle('show'); }); 

JSFIDDLE DEMO


OR


  • just remove the 'show' on toggle , just use

    $('#button1content').toggle();

like this:

 $('#buttons1').on('click', function(event) { $('#button1content').toggle(); var wasVisible = $("#button1content").is(":visible"); if(!wasVisible) { $("#buttons1").css("opacity", "0.5"); } }); 

JSFIDDLE DEMO

+2
source

The if statement is not available because you always showed button1content

  $('#button1content').toggle('show'); 

So var wasVisible = $("#button1content").is(":visible"); will always be true

+1
source

All Articles