Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write this jQuery snippet more beautiful

These two functions should be fired on load and on resize. I'm wondering how to write it more compact and beautiful. Any ideas?

$(document).ready(function() {
    fullScreen();
    footer();
    $(window).resize(function() {
        fullScreen();
        footer();
    });
});
like image 738
Thomas Avatar asked Jan 04 '11 11:01

Thomas


3 Answers

You can trigger the resize event right after you register your handler:

$(document).ready(function() {
    $(window).resize(function() {  // Register handler.
        fullScreen();
        footer();
    }).resize();                   // Trigger event.
});
like image 93
Frédéric Hamidi Avatar answered Oct 05 '22 02:10

Frédéric Hamidi


Well, you could combine them into one function, but I'm not sure it's more "beautiful":

jQuery(function($) {

    both();
    $(window).resize(both);

    function both() {
        fullScreen();
        footer();
    }
});

It does address the issue of not repeating yourself.

Off-topic: I also switched $(document).ready(function(){... to jQuery(function($){.... It does the same thing, but makes the quoted code compatible with noConflict, if that's useful. If you'll never want noConflict compatibility, you can use $(function(){... instead, but hey, for six extra chars...

like image 21
T.J. Crowder Avatar answered Oct 05 '22 03:10

T.J. Crowder


$(function() {
    function both() {
        fullScreen();
        footer();
    }

    both();
    $(window).resize(both);
});
like image 39
Marcus Whybrow Avatar answered Oct 05 '22 02:10

Marcus Whybrow