Question

I'm writing a function for a WordPress site, following the guidelines based on WordPress Codex http://codex.wordpress.org/Function_Reference/wp_enqueue_script#jQuery_noConflict_Wrappers

So here's my script, which I want to execute immediately, instead of waiting for the DOM ready event:

(function($) {
    if ($('#wpadminbar').length > 0) {
        $('#menu').css('top', $('#wpadminbar').height()+'px');
            $('.pure-menu-link').css('top', $('#wpadminbar').height()+'px');
    }
})(jQuery);

Now I would also like to re-run this function anytime the screen is resized, something like:

(function($) {
    if ($('#wpadminbar').length > 0) {
        $('#menu').css('top', $('#wpadminbar').height()+'px');
            $('.pure-menu-link').css('top', $('#wpadminbar').height()+'px');
    }
    $(window).resize(function($));
})(jQuery);

But obviously that throws a syntax error.

My question is, how do I execute function, then re-execute it on window resize? Do I need a loop?

Was it helpful?

Solution

Use a DOM ready function, what you have is just a IIFE, then attach an actual event handler on resize, and trigger the event to fire it on pageload :

jQuery(function($) {
    $(window).on('resize', function() {
        if ($('#wpadminbar').length) {
            $('#menu, .pure-menu-link').css('top', $('#wpadminbar').height());
        }
    }).trigger('resize');
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top