Reputation: 79
I created a div that has the full height of it's content set to 500px. First 200px of the 500px is, lets say, a preview. So I set it's height to 200px and overflow: hidden
. I then added this script:
<div class="stretcher">
<script type="text/javascript">
$('.stretcher').toggle(
function(){
$(this).animate({'height': '500px'}, 300);
},
function(){
$(this).animate({'height': '200px'}, 300);
}
);
</script>
That works but the problem is that I need the contents of the div to be clickable. However, with this script wherever I click it either expands the div or returns it back to the original 200px.
Any idea how I could do it? Maybe adding icons of arrow up and down or something.
Upvotes: 0
Views: 328
Reputation: 24703
You could wrap your code in a function that has an exact match. As @adeneo points out. An example below using your existing code in this manner.
$('.stretcher').on('click', function(e) {
if (e.target === this) {
$('.stretcher').toggle(
function(){
$(this).animate({'height': '500px'}, 300);
},
function(){
$(this).animate({'height': '200px'}, 300);
}
);
}
});
Upvotes: 0
Reputation: 318202
The toggle()
function used that way is deprecated and removed in newer versions of jQuery, use a flag instead :
$('.stretcher').on('click', function(e) {
if (e.target === this) {
var h = $(this).height() > 220;
$(this).animate({'height': ( h ? 200 : 500 ) }, 300);
}
});
Checking if the target
equals this
stops any problems when clicking other elements inside .strecher
Upvotes: 4
Reputation: 26143
Try this...
<div class="stretcher">
<div class="clickable"></div>
</div>
<script type="text/javascript">
$('.clickable').toggle(
function()
{
$(this).parent().animate({'height': '500px'}, 300);
},
function()
{
$(this).parent().animate({'height': '200px'}, 300);
}
);
</script>
You have an area called clickable
and when you click that it animates the parent container div, but it won't do it when you click the div itself.
Upvotes: 2