Reputation: 1273
$(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
Upvotes: 4
Views: 18243
Reputation: 11381
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/
Upvotes: 4
Reputation: 318342
You could just check if the element is visible:
$(document).ready(function () {
$('#AddCity').hide();
$('#AddCityA').click(function () {
var state = $('#AddCity').is(':visible');
$('#AddCity')[state?'hide':'slideDown'](state ? 0 : 'slow');
});
});
For a much simpler approach, you could slide the element both ways :
$('#AddCity').hide();
$('#AddCityA').on('click', function () {
$('#AddCity').slideToggle('slow');
});
Upvotes: 3