Search code examples
jquerytogglewindow-resizeouterheight

jQuery - Recalculate variable on window resize and re-run function


I wrote a function that hides and toggle a top bar div:

jQuery(document).ready(function($) {

        $.fn.myTopBar = function() {

                var sipPosTop = 0;
                var topDivHeight = $("#top").outerHeight();

                $('#top').css('top' , -topDivHeight+10).show().animate({top: '+=0'}, 2000);


                $("#top-toggle").click(function(e) {
                    e.preventDefault();
                    $("#top").animate({ top: sipPosTop }, 200, 'linear', function() {
                        if(sipPosTop == 0) { sipPosTop = -topDivHeight+10; }
                        else { sipPosTop = 0; }
                    });
                });
        };
});

Works nice on page load, but on window resize the #top div height changes and it breaks the layout. How can I recalculate it and re-run the function on window resize? I tried the following:

jQuery(document).ready(function($){
    $.fn.myTopBar();
});

jQuery(window).resize(function($){
    $.fn.myTopBar();
});

But does not work. Thanks for any help


Solution

  • Edit -- Based upon your comments, I've written this plugin that (hopefully) will have the functionality that you are seeking. If anything, you may be able to extract some information on how to go about doing it.

    Call the plugin with this --

    $(function () {
        $('.someFlyoutContainerClass').flyout({
            flyButton : $('.someButtonClass'), // button that toggles the flyout
            topOffset : 50, // (px) offset from the top of the window
            fade : { // (fade speeds/durations) -- remove object if not needed
                inSpeed : 350,
                easingIn : 'swing', // by removing easing, it will default to linear
                outSpeed: 250,
                easingOut : 'swing'            
            },
            slide : { // (slide speeds/durations) -- remove object if not needed
                inSpeed : 350,
                easingIn : 'swing',
                outSpeed : 250,
                easingOut : 'swing'      
            },
            closeButton : $('.close-flyout'), // you may remove if not needed
            clickOffClose: true // click anywhere but modal/flyout to close it
        });
    });
    

    Here is a working version of the script -- (updated 12/13) http://jsfiddle.net/jmsessink/fC8ht/5/

    I hope this helps and let me know if you have any questions.