Reputation: 23
I made a bar graph with some divs. Now I'm trying to get that when you hover one of the bars, it grows in height. I got this part working, but my problem is that when I hover it a few times it keeps on growing and doesn't go back to the original height I set. How do I fix this?
css:
@keyframes grow-column {0% {transform: translateY(100%);} 100% {transform: translateY(0);}}
.chart {
height: 500px;
width: 100%;
display: flex;
flex-direction: column;
}
.bars {
flex: 1;
display: flex;
flex-direction: row;
align-items: flex-end;
overflow: hidden;
border-bottom: 4px solid #bab3b3;
}
.bar {
flex: 1;
border-bottom: none;
margin: 0 5px;
animation: grow-column 3s;
background-color: red;
}
html:
<div class="chart">
<div class="bars">
<div class="bar" style="height:32%;"></div>
<div class="bar" style="height:42%;"></div>
<div class="bar" style="height:47%;"></div>
<div class="bar" style="height:51%;"></div>
<div class="bar" style="height:53%;"></div>
<div class="bar" style="height:56%;"></div>
<div class="bar" style="height:58%;"></div>
<div class="bar" style="height:67%;"></div>
<div class="bar" style="height:76%;"></div>
<div class="bar" style="height:76%;"></div>
<div class="bar" style="height:82%;"></div>
<div class="bar" style="height:84%;"></div>
<div class="bar" style="height:86%;"></div>
<div class="bar" style="height:94%;"></div>
</div>
</div>
javascript:
$(".bar").on('mouseover', function() {
var height = calculateHeight($(this), 10);
$(this).attr('original', $(this).height());
$(this).animate({height: height + "px"}, 250);
}).on('mouseleave', function() {
var height = $(this).attr('original');
$(this).attr('original', null); // deze kan weg
$(this).animate({height: height + "px"}, 250);
});
function calculateHeight(element, amount) {
var parentHeight = element.parent().height();
var height = element.height() + amount;
return (parentHeight < height) ? parentHeight : height;
}
Upvotes: 2
Views: 469
Reputation: 2515
In your onMouseOver
event you set the value of 'original'
to the newly calculated height! So, in onMouseLeave
you simply get the newly set value and apply it to the element's height, which means the height does not change. When you hover again the new (wrong) height is taken and you calculate the new height with this wrong value.
Instead you could work with a global variable, like this:
var originalHeight;
$(".bar").on('mouseover', function() {
originalHeight = $(this).height();
var height = calculateHeight($(this), 10);
$(this).animate({height: height + "px"}, 250);
}).on('mouseleave', function() {
$(this).animate({height: originalHeight + "px"}, 250);
});
Upvotes: 2