jquery hide() and slideDown()

Shirker picture Shirker · Jun 23, 2013 · Viewed 15.4k times · Source
$(document).ready(function(){
 $('#AddCity').hide();
 $('#AddCityA').click(function(){
     if ( AddCityVar==1 ){
         $('#AddCity').hide();
         var AddCityVar=0;
     }else{
           $('#AddCity').slideDown("slow");
           var AddCityVar=1;
     }
  });

I cant figure this out, why div with ID #AddCity is opening on first click on #AddCityA link, but never goes hide on second click? Does $('#AddCityA').click(function() work only once?

<a href="#" id="AddCityA">Add City</a> 

<div id="AddCity">
    here some code
</div>

Thanks for any help

Answer

krishwader picture krishwader · Jun 23, 2013

You seem to be re-initialisng AddCityVar everytime you assign some value to it. You need to have it outside the scope of the click function :

$(document).ready(function(){
    $('#AddCity').hide();
    var AddCityVar= 0;
    $('#AddCityA').click(function(){
      if ( AddCityVar==1 ) {
         $('#AddCity').hide();
         AddCityVar=0;
      }
      else {
         $('#AddCity').slideDown("slow");
         AddCityVar=1;
      }
    });
 });

But, as roasted mentioned, it neednt have a variable to do this. You can just use slideToggle :

$('#AddCityA').click(function () {
  $('#AddCity').slideToggle("slow");
});

A Demo : http://jsfiddle.net/hungerpain/9cdKL/