I'm trying to create a logo image that animates to 50% size when window is scrolled. My problem is that the animation runs several times while the window scrolls. How can I make it animate once while the window is scrolled > 62px and once again if the window is scrolled back above 62px? I tried adding classes and remove them but without luck. I searched SO but couldn't find a duplicate or similar question (my bad if there is!).
JSFiddle here: http://jsfiddle.net/jtheman/kEtPd/ (added some extra css in jsfiddle to simulate my real project)
Relevant HTML:
<body>
<header>
<div id="logo">
<img src="/img/logo.png">
</div>
...
CSS:
header { position:relative; }
header #logo { position:absolute; top: 62px; left: 0; width: 365px; height: 53px; }
header #logo img { position:absolute; bottom: 0; left: 0; width: 365px; height: 53px; }
And my jQuery:
$(window).scroll( function() {
var scrollpos = $(window).scrollTop();
if (scrollpos > 62)
{
$('#logo img').stop().animate({ 'width': '182px', 'height': '26px'},1000);
}
else
{
$('#logo img').stop().animate({ 'width': '365px', 'height': '53px'},200);
}
});
You should check the width is still original size (365px) so that it only animates if the image hasn't already started being resized:
if (scrollpos > 62)
{
if ($('#logo img').width() == 365){
$('header').css({'position':'fixed','top':'-62px'});
$('#logo img').stop().animate({ 'width': '182px', 'height': '26px'},1000);
}
}
-- SEE WORKING DEMO --
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With