jQuery, window.width () native and window.on resize in the same condition

3

I would like to know if a better way is possible than this, as it spared the repetition of code:

I usually do:

if($(window).width() > 800) {

// BLAH BLAH BLAH

}

$(window).resize(function(){

    if($(window).width() > 800) {

        // BLAH BLAH BLAH

    }

});

This does not seem to be a viable / good code implementation since I am repeating code (BLAH BLAH BLAH), is there any way to put the two conditions within it?

    
asked by anonymous 23.10.2014 / 15:02

2 answers

3

Create a function and execute the function in both cases ...

function blah() {
    // BLAH BLAH BLAH
}

if($(window).width() > 800) {

    blah();

}

$(window).resize(function(){

    if($(window).width() > 800) {

        blah();

    }

});

or completely eliminating the repetition:

function blah() {
    if($(window).width() > 800) {
        // BLAH BLAH BLAH
    }
}

blah();

$(window).resize(function(){
    blah();
});

Note: Always declare the function before it is called ...

    
23.10.2014 / 15:14
2

You can further reduce your code.

$(window).on("resize", function(){
    if($(this).width() > 800) {

        // BLAH BLAH BLAH

    }
});
$(window).trigger('resize'); // Aqui você usa o 'trigger' para chamar o resize manualmente

Using the trigger you can manually call resize when the screen loads, it gets much cleaner

    
23.10.2014 / 23:03