0
$(function(){
    if($(window).width()>1100){
        $("#logo").hover(function(){
            $(this).animate({paddingTop:"0px",paddingBottom:"20px"},200);
            },function(){
                $(this).animate({paddingTop:"20px",paddingBottom:"0"},200);
                });
        }
    $(window).resize(function(){
        if($(window).width()>1100){
            $("#logo").hover(function(){
                $(this).animate({paddingTop:"0px",paddingBottom:"20px"},200);
                },function(){
                    $(this).animate({paddingTop:"20px",paddingBottom:"0"},200);
                    });
            }
        });
    });

Right now, this animation is only executed when the window width is greater than 1100 px but it requires a refresh of the browser if the browser is resized on the fly. How can this be fixed so that a browser refresh is not needed?

oceanic815
  • 483
  • 2
  • 9
  • 20

2 Answers2

1

Register/Unregister the handlers in resize event based on the window size.

$(function () {
    $(window).resize(function () {
        if ($(window).width() > 1100) {
            $("#logo").on('mouseenter.anim', function () {
                $(this).animate({
                    paddingTop: "0px",
                    paddingBottom: "20px"
                }, 200);
            }).on('mouseleave.anim', function () {
                $(this).animate({
                    paddingTop: "20px",
                    paddingBottom: "0"
                }, 200);
            });
        } else {
            $("#logo").off('mouseenter.anim mouseleave.anim');
        }
    }).resize();
});

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • When the window collapses, the animation is successfully deactivated. But when the window is expanded again, reactivating the animation, it becomes very choppy/laggy. Any ideas why? – oceanic815 Feb 24 '14 at 01:00
  • It lags in the fiddle also. Is this something that I just have to live with? – oceanic815 Feb 24 '14 at 01:06
  • That tweak fixed it. Your'e a stud. – oceanic815 Feb 24 '14 at 01:20
  • How would you change this script to use the viewport width instead of the document width so that it matches the CSS media query? – oceanic815 Feb 24 '14 at 01:37
  • @oceanic815 I haven't used it before anyway try http://stackoverflow.com/questions/18546067/why-is-the-window-width-smaller-than-the-viewport-width-set-in-media-queries or http://www.matanich.com/2013/01/07/viewport-size/ – Arun P Johny Feb 24 '14 at 02:18
0

Name your function, and listen to the resize event like so:

$(window).on("resize", yourfunction());
Hoff
  • 38,776
  • 17
  • 74
  • 99