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

Asked

Viewed 492 times

3

I wonder if a better way is possible than this, as it would save the repetition of code:

usually do:

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

// BLAH BLAH BLAH

}

$(window).resize(function(){

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

        // BLAH BLAH BLAH

    }

});

This does not seem to me a viable/good implementation of code because I am repeating code (BLAH BLAH BLAH), there will be some way to put the two conditions within the same?

2 answers

3


Create a function and run 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...

  • But I have other duties within the BLAH BLAH BLAH

  • @Miguel has no problem, run everything within the new function normally...

  • Obgado, I had thought about it but I thought of 'php', which is not nested functions. Excellent

  • @Miguel In php you can even run the function itself on it...

  • Yes, but not create/declare functions within other

  • 1

    It does, I just tested it. But obviously the functions declared within another function will only be available after the "mother" function is called at least once... (It is necessary to check re statement)

  • Obgado, you’re right, within a class/object gives also?

Show 2 more comments

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 Trigger you can call resize manually when the screen loads, it is much cleaner

Browser other questions tagged

You are not signed in. Login or sign up in order to post.