Rvervuurt
Rvervuurt

Reputation: 8963

jQuery function on resize and on load without copy/pasting

I have the following piece of jQuery that checks the width of the browser on load, and runs accordingly. But to make sure the div keeps the right size when the browser-width is changed, I have placed the same piece of code in $(window).resize(function() {..});.

This seems very weird and unnecessary, so I'm wondering how I can place the code only once and have it run on both .resize and on load.

var windowWidth = $(window).width();
if(windowWidth > 768 && windowWidth < 1223){
    $('.banner_image').show();
    $('.banner_image').height($('.banner .span3').height());
    $('.banner .span12 img').hide();            
}
else {
    $('.banner_image').hide();
    $('.banner .span12 img').show();
}

$(window).resize(function() {
var windowWidth = $(window).width();
    if(windowWidth > 768 && windowWidth < 1223){
        $('.banner_image').show();
        $('.banner_image').height($('.banner .span3').height());
        $('.banner .span12 img').hide();                
    }
    else {
        $('.banner_image').hide();
        $('.banner .span12 img').show();
    }
});

Upvotes: 0

Views: 37

Answers (2)

kapantzak
kapantzak

Reputation: 11750

Just store the function in a variable and execute it everytime you want to:

$(window).load(function() {
   wFunc();
});    

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

var wFunc = function() {
   var windowWidth = $(window).width();
   if(windowWidth > 768 && windowWidth < 1223){
    $('.banner_image').show();
    $('.banner_image').height($('.banner .span3').height());
    $('.banner .span12 img').hide();            
   }
   else {
    $('.banner_image').hide();
    $('.banner .span12 img').show();
   }
}

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82241

You can trigger the event after binding the event:

$(window).resize(function() {
var windowWidth = $(window).width();
if(windowWidth > 768 && windowWidth < 1223){
    $('.banner_image').show();
    $('.banner_image').height($('.banner .span3').height());
    $('.banner .span12 img').hide();                
}
else {
    $('.banner_image').hide();
    $('.banner .span12 img').show();
}).resize();//resize to trigger on load

Working Demo

Upvotes: 1

Related Questions