Reputation: 683
I've recently implemented a small box on my website at the bottom of the page to expand when the mouse hovers over it... This is the code and it all works great.
CSS
#box{
position:absolute;
width:300px;
height:20px;
left: 33%;
right: 33%;
min-width: 32%;
bottom:0;
background-color: #353535;
}
javascript
$('#box').hover(function() {
$(this).animate({
height: '220px'
}, 150);
},function() {
$(this).animate({
height: '20px'
}, 500);
});
But I'm curious about how I would go about changing this to open and close on a click rather than the mouse hovering over it?
I've edited it to...
$('#box').click(function() {
$(this).animate({
height: '220px'
}, 150);
},function() {
$(this).animate({
height: '20px'
}, 500);
});
And this works to open the box. But I can't get it to close again with another click.
So close yet so far! :P
Upvotes: 2
Views: 4470
Reputation: 6184
this should work
$('#box').toggle(function() {
$(this).animate({
height: '220px'
}, 150);
},function() {
$(this).animate({
height: '20px'
}, 500);
});
Upvotes: 2
Reputation: 36999
You can probably just use the toggle event handler instead of the click event like so:
$('#box').toggle(function() {...}, function() {...});
Upvotes: 2
Reputation: 382656
You can do:
$('#box').click(function() {
if ($(this).is(':visible')) {
$(this).hide();
return;
}
$(this).animate({height: '220px'}, 150);
});
On the click, it will hide the element if visible else animate it.
Upvotes: 1