Reputation: 7971
I have simple hide and show function but it is not working. any help would be appreciated
<head>
<script type="text/javascript">
$(function(){
$('a').click(function(){
var visible= false;
if(visible){
$('div').hide('slow')
}
else {
$('div').show('slow')
}
visible=!visible;
})
})
</script>
</head>
<body>
<div style="background:#F00; width:500px; height:50px"></div>
<a href="#">hide</a>
<div class="append"></div>
</body>
Upvotes: 0
Views: 88
Reputation: 3130
Try using toggle
instead. Check out the second example here:
Here's the example:
<!DOCTYPE html>
<html>
<head>
<style>
p { background:#dad;
font-weight:bold;
font-size:16px;
}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<button>Toggle 'em</button>
<p>Hiya</p>
<p>Such interesting text, eh?</p>
<script>
$("button").click(function () {
$("p").toggle("slow");
});
</script>
</body>
</html>
Upvotes: 0
Reputation: 8583
jQuery has a builtin hide/show method: .toggle(). It shows your element when it is hidden and vice versa.
Upvotes: 1
Reputation: 816262
Declare and initialise visible
outside the event handler:
var visible= false;
$('a').click(function(){
if(visible){
$('div').hide('slow')
}
else {
$('div').show('slow')
}
visible=!visible;
});
Otherwise you are initialising visible
with false
every time the event handler is executed, so if(visible)
will never be true.
However, you can also use .toggle
[docs] to avoid having an additional status variable:
$('a').click(function(){
$('div').toggle();
});
Upvotes: 4
Reputation: 35039
The problem are these lines:
var visible= false;
if(visible){
$('div').hide('slow')
}
visible
will always be false in this context, thus your div will never be hidden.
Upvotes: 0